Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected behaviour when using sizeof operator [duplicate]

Tags:

c

sizeof

#include <stdio.h>
#include <stdlib.h>

typedef struct StupidAssignment{
    long length;
    char* destination_ip;
    char* destination_port;
    long timestamp;
    long uid;
    char* message;
}packet;

void main(){
    int number_of_packets=10;int i;
    packet* all_packets[number_of_packets];
    for(i=0;i<number_of_packets;i+=1)all_packets[i]=malloc(sizeof packet);
}

The above snippet does not compile with the following error:-

reciever.c: In function ‘main’:
reciever.c:16:64: error: expected expression before ‘packet’
  for(i=0;i<number_of_packets;i+=1)all_packets[i]=malloc(sizeof packet);

However, the following code does compile:-

#include <stdio.h>
#include <stdlib.h>

typedef struct StupidAssignment{
    long length;
    char* destination_ip;
    char* destination_port;
    long timestamp;
    long uid;
    char* message;
}packet;

void main(){
    int number_of_packets=10;int i;
    packet* all_packets[number_of_packets];
    for(i=0;i<number_of_packets;i+=1)all_packets[i]=malloc(sizeof(packet));
}

The only difference being sizeof(packet) and sizeof packet.

On a previous answer, I came to learn that sizeof is just an operator like return so the parenthesis was optional.

I obviously missed something so can someone explain this behaviour to me?

like image 975
asds_asds Avatar asked Oct 17 '25 14:10

asds_asds


2 Answers

When using the sizeof operator with a type, you must place the type in parentheses.

When using the sizeof operator with a variable, you may omit the parentheses.


See §6.5.3 Unary operators and §6.5.3.4 The sizeof and _Alignof operators in the C11 draft. Credit to @JonathanLeffler for identifying the sections.

like image 89
rtx13 Avatar answered Oct 20 '25 05:10

rtx13


sizeof is an operator. It just uses parenthesis to differentiate between data types and variables.

sizeof packet; //Error
sizeof(packet); //Compiles

packet p;
sizeof p; //No error
like image 21
Abhay Aravinda Avatar answered Oct 20 '25 04:10

Abhay Aravinda