0

I have the following snippet

#include <stdio.h>
#include <string.h>
#define SIZE 3
typedef struct node{
    char *name;
    int id;
} Rec;
int main() {
    Rec n[SIZE], *p;
    int i;
    char *s[]= { "one", "two","three"};

    for (i = 0; i < SIZE; i++){
        strcpy(n[i].name, s[i]);
        //n[i].id = i;
    }
    p = n;
    for (i = 0; i < SIZE; i++){
        //printf("%2d %s\n", p->id, p->name);
        p++;
    }
    getchar();
}

I've been sitting on this for like an hour now, and I can't put my finger on the problem. This program gets kicked out when it hits the strcpy(). I do not know how to solve this, tho I get the feeling that there's a problem with n's allocation. I did tried to convert it to malloc, but results stayed the same..

Thanks in advance !

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Aviad
  • 3,424
  • 3
  • 14
  • 21

1 Answers1

1

You have not allocated memory for name member for your structs. You need to allocate memory for them

 for (i = 0; i < SIZE; i++){
    n[i].name = malloc(strlen(s[i]) + 1);
}
haccks
  • 104,019
  • 25
  • 176
  • 264