简体   繁体   English

c:在数据结构内的元素上使用 strcpy()

[英]c: using strcpy() on an element inside a data structure

i am currently learning cs50.我现在正在学习cs50。 i am currently studying data structures..i came across a problem...please see if you could help:我目前正在研究数据结构..我遇到了一个问题...请看看您是否可以提供帮助:

#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;
}

Use p->name = "hasan";使用p->name = "hasan"; instead of strcpy(p->name, "hasan");而不是strcpy(p->name, "hasan"); . .

The name in struct node is a pointer which can point to an array of char. struct node中的name是一个指针,可以指向一个 char 数组。

It didn't have allocated memory space for the char array.它没有为 char 数组分配 memory 空间。

you didn't initialize your struct.你没有初始化你的结构。 Either initialize the struct inside 'struct node' with a constructor, or initialize inside main使用构造函数初始化“结构节点”内部的结构,或者在 main 内部初始化

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM