相关疑难解决方法(0)

使用 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);
}
Run Code Online (Sandbox Code Playgroud)

上面的代码片段不会编译,并出现以下错误:-

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);
Run Code Online (Sandbox Code Playgroud)

但是,以下代码确实可以编译:-

#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));
}
Run Code Online (Sandbox Code Playgroud)

唯一的区别是sizeof(packet)sizeof packet

在上一个答案中,我了解到这 …

c sizeof

3
推荐指数
1
解决办法
82
查看次数

标签 统计

c ×1

sizeof ×1