问题
#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?
回答1:
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.
回答2:
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
回答3:
According to the documentation:
sizeof( type )
sizeof expression
So, types need parentheses, expressions do not.
来源:https://stackoverflow.com/questions/60955287/unexpected-behaviour-when-using-sizeof-operator