Unexpected behaviour when using sizeof operator

Viewed 101
#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?

3 Answers

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

According to the documentation:

sizeof( type )
sizeof expression

So, types need parentheses, expressions do not.

Related