user1730056
user1730056

Reputation: 623

How to access elements in an array of structs (not global)

Trying to continue with my assignment but would like to sidetrack and figure out how array of structs work. Not sure if I'm not looking hard enough but I can't seem to find an answer.

Let's say I have one source file, main.c

#include "data.h" //this contains the struct data.
newPerson person[20];

int mainMenu(){
    addName();      
}
void addName(){
    strcpy(person[0].firstName, "George");
}

Doing it this way, I'm able to access the array of struct, however isn't this method considered taboo since my array of person is a global variable?

I then tried moving the array initialization into the main function instead

#include "data.h" //this contains the struct data.

int mainMenu(){
    newPerson person[20];
    addName();      
}
void addName(){
    strcpy(person[0].firstName, "George");
}

Doing it this way, when I get to the addName() function, I get a 'person undeclared' error. How can I access the person[] array outside of its function without making it a global variable? Thank for the help in advance. Below I have the example data.h included if needed.

data.h

typedef struct person{
    char firstName[20];
    char familyName[20];
    char telephoneNum[20];
}newPerson;

Upvotes: 0

Views: 56

Answers (2)

Ósky F J
Ósky F J

Reputation: 7

Yeah, pass the variable, person in this case.

person is an array of struct newPerson.

to pass arrays as parameters you should define the function like this

//Option 1, the last dimension without number
void addName(newPerson person[]){
    //...
}

//Option 2, as a pointer, but it neets a cast on the call (newPerson*)
void addName(newPerson *person){ //I prefer option 1
    //...
}

Upvotes: 0

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53036

Just pass parameters to the addName() function.

Example

#include "data.h" //this contains the struct data.

int mainMenu(){
    newPerson person[20];
    addName(person, 0, "George");      
}

void addName(newPerson *person, unsigned int index, const char *const name) {
    if ((person == NULL) || (index >= 20))
        return; /*                     ^ this number could be specified with a macro */
                /*                       or via a parameter                          */
    strcpy(person[index].firstName, name);
}

Upvotes: 2

Related Questions