[英]pass scanf value to struct pointer Segmentation Fault
我想要做的就是使用用户输入使用结构指针进行基本打印。 当我尝试使用下面的代码时,我遇到了segmentation fault
。 我是c的新手,不管怎样,谢谢。
typedef struct {
int *licenseNum;
char *name;
char *region;
} City;
typedef struct {
struct Node *current;
struct Node *head;
struct Node *tail;
struct Node *next;
struct Node *secondNext;
City *data;
} Node;
int main()
{
Node *node = malloc(sizeof(Node));
City *city = malloc(sizeof(City));
puts("License number of the City: ");
scanf("%d", &(node -> data -> licenseNum));
printf("%d", node -> data -> licenseNum);
return 0;
}
您没有在node
设置data
。
Node * node = malloc(sizeof(Node));
City * city = malloc(sizeof(City));
// node->data is not yet defined!
// It has a random value! You must first initialize it:
node->data = city;
此外,您不应在此处使用malloc
,因为malloc
分配的malloc
具有随机值。 如果您确实在使用之前初始化struct
具有有意义值的所有指针,请仅使用malloc
。 使用calloc
更安全:
Node * node = calloc(1, sizeof(Node));
City * city = calloc(1, sizeof(City));
node->data = city;
calloc
工作方式与malloc
类似,但它保证返回的内存全部设置为零(所有int值都为0
,所有指针都为NULL
)。 calloc
的第一个参数(上面代码中的1
)是你想要分配的项目数,这里只是一个。 例如calloc(5, sizeof(City))
将在一个块中为5个城市分配内存,例如:
Cities * cities = calloc(5, sizeof(City));
cities[0].name = "New York";
cities[1].name = "London";
// ... and so on
您没有初始化node->data
。
您为node
分配了内存,但没有为node->data
分配内存。
你可能想这样做: node->data = city
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.