0

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;
}
hussein
  • 11
  • 2
  • The marked line works but the next line causes undefined behaviour as you try to `strcpy` into space which is not writable – M.M Sep 19 '22 at 23:37

1 Answers1

2

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.

cpprust
  • 110
  • 4