0

I'm brand new to C and am trying to create a global array that will hold pointers to structs:

person* persons[n];

However, I need to make the above a global variable. To do that, I need to declare it outside of all functions. But how can I do that without knowing what n will be? Really lost here, any help would be appreciated!

The below is what I'm ultimately trying to accomplish:

person* persons[];

function () {
    initialize global array here
}
0

1 Answer 1

3

You use a pointer of a pointers and call malloc in an init function.

person **persons;
int n = 42;

void init(void)
{
    persons = malloc(n * sizeof *persons);
    if (!persons) {
        /* handle malloc failure here */
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

Can I still use the indices to refer to structs from this new pointer of pointers (as I would in a regular array that holds pointers)?
@Vimzy yes, for example persons[0] is the first person * of the array object.
@Nevermind, that was my bad. My only problem now is can I still do code like this: "persons[h] = (person *) malloc(sizeof(person))" I'm a little new to this "pointer to pointer" thing with structs.
Because ultimately my code needs this: "persons[h]->name = .." but I'm not sure if this will work?
@Vimzy yes it will but be sure to initialize all the persons[i] first using malloc as well.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.