简体   繁体   中英

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

i am currently learning 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"; instead of strcpy(p->name, "hasan"); .

The name in struct node is a pointer which can point to an array of char.

It didn't have allocated memory space for the char array.

you didn't initialize your struct. Either initialize the struct inside 'struct node' with a constructor, or initialize inside main

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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