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

Viewed 22

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;
}
2 Answers

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

Related