[英]c: using strcpy() on an element inside a data structure
我现在正在学习cs50。 我目前正在研究数据结构..我遇到了一个问题...请看看您是否可以提供帮助:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node{
char *name;
int age;
};
typedef struct node node;
int main(){
node *p=malloc(sizeof(node));
if (p==NULL){
return 1;
}
p->name="hussein";
p->age=32;
printf("staff1: %s, %d\n", p->name, p->age); //why doesn't this line of code work? program crashes here
strcpy(p->name, "hasan");
printf("staff1: %s, %d\n", p->name, p->age);
free(p);
return 0;
}
使用p->name = "hasan";
而不是strcpy(p->name, "hasan");
.
struct node
中的name
是一个指针,可以指向一个 char 数组。
它没有为 char 数组分配 memory 空间。
你没有初始化你的结构。 使用构造函数初始化“结构节点”内部的结构,或者在 main 内部初始化
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.