Matze
Matze

Reputation: 75

C - dynamic array of typedef struct with in-function malloc

I'm stuck again and have huge issues understanding whats going on in my following code examples:

//Filename main.c

    #include<stdio.h>
    #include "entries.h"

    int main(){

        playerEntry *Entry;

        printf("Number of Entries: %d",readPlayerList(&Entry));

        return 0;
    }

It simply calls the function and prints out the result and should be able to handle the entries made by the function in *Entry (which should be an array by then)

//Filename entries.h
#ifndef ENTRIES_H_
#define ENTRIES_H_

typedef struct {
    char Name[25];
    int Score;
}playerEntry;


int readPlayerList(playerEntry* *feld);


#endif /* ENTRIES_H_ */

Now here's the typedef and the function prototype, kept pretty simple and straight forward because its just a sample of the (for me ;( ) yet unknown problem that produces crashes

//Filename readPlayerList.c
    #include<string.h>
    #include<stdlib.h>
    #include "entries.h"

    int readPlayerList(playerEntry* *feld) {

        int i = 0, Score = 5001;
        char Name[25] = "Rasputin";

        *feld = malloc(4 * sizeof(playerEntry));

        for(i= 0; i < 3; i++){
            strcpy(feld[i] ->Name, Name);
            feld[i]->Score = Score;
        }

        return i;
    }

And that is where the crap happens.

I dont even know how to call it properly! :(

My struct is allocated by malloc, but only as a one elemented "array", at least thats what I think. It always works nice for one run, but whenever I try to write on another index such as feld[1].Name it crashes the program, because there's obviously no space allocated. How to solve it by keeping the structure as shown?

It was hard enough to figure out how malloc could be used inside a function to actually allocate something that can be used outside the function. But I'm not even sure if that's the proper way to do it. I've really read a lot today to figure it out somehow but there's just nothing that quite exactly fits in there, and I cannot fill the gap on my own. Please help, and thanks in advance! :)

Upvotes: 1

Views: 653

Answers (1)

user3079266
user3079266

Reputation:

strcpy(feld[i] ->Name, Name);
feld[i]->Score = Score;

should be

strcpy( ( (*feld)[i] ).Name, Name);
( (*feld)[i] ).Score = Score;

(redundant parens added for easier understanding)

It's simple: feld is not a pointer to a heap array, but you're using it like one. It's actually a pointer to a pointer to a heap array. So, you're basically iterating through the wrong thing.

In my example above, you first dereference feld, i.e. get the pointer which points to your allocated array.

Upvotes: 1

Related Questions