Incorrectly assigned C pointers

I create an array of structures called "mcguffins" and I get a really strange error.

//prints the info in a mcguffin void printInfo(int i,struct mcguffin * new) { printf("%d \tNum: %d\t Word: %s\n", i, new->num, new->word); } //creates a new mcguffin struct mcguffin * addMG(int n, char * w) { printf("Expected output:\n\tNum: %d\tWord: %s\n", n, w); struct mcguffin * new; new = malloc(sizeof *new); new->num = n; strncpy(new->word, w, sizeof(char[20])); printf("Actual output: \n\t"); printInfo(1, new); return new; } //creates a list of mcguffin pointers, and sets these pointers to new mcguffins struct mcguffin ** writeList() { struct mcguffin ** list = malloc(10 * sizeof(*list)); list[0] = addMG(2, "Jeter"); list[1] = addMG(14, "Granderson"); list[2] = addMG(25, "Teixeira"); list[3] = addMG(13, "Rodriguez"); list[4] = addMG(24, "Cano"); list[5] = addMG(33, "Swisher"); list[6] = addMG(55, "Martin"); list[7] = addMG(20, "Posada"); list[8] = addMG(11, "Gardner"); list[9] = addMG(42, "Mo"); return list; } 

For some reason, list [0] and list [1] are not assigned to the created structures, but list [2] through list [9]. addMG works fine and creates structures for list [0] and list [1], but for some reason, when I try to use printInfo on them, instead of printing information about structures, it prints the memory address,> num should go and do not output anything for the new-> word.

 0 Num: 30519472 Word: 1 Num: 30519600 Word: 2 Num: 25 Word: Teixeira 3 Num: 13 Word: Rodriguez 4 Num: 24 Word: Cano 5 Num: 33 Word: Swisher 6 Num: 55 Word: Martin 7 Num: 20 Word: Posada 8 Num: 11 Word: Gardner 9 Num: 42 Word: Mo 

This is probably some kind of stupid mistake, because I'm new to C, but any help would be appreciated.

EDIT: To clarify, mcguffins are declared in a separate header file, for example:

 struct mcguffin { int num; char word[20]; }; 
+4
source share
1 answer
 new = (struct mcguffin *)malloc(sizeof(struct mcguffin *)); ^^ 

You allocate enough space for a pointer to mcguffin . Lower * . Better yet, change it to:

 new = malloc(sizeof *new); 

Your list distribution is also incorrect. You must highlight:

 struct mcguffin **list = malloc(10 * sizeof *list); 
+2
source

Source: https://habr.com/ru/post/1446815/


All Articles