如何访问结构数组中的元素(非全局)

时间:2015-02-20 21:44:41

标签: c arrays struct

尝试继续我的任务,但是想要侧视并弄清楚结构数组的工作原理。不确定我是不是看起来不够努力,但似乎无法找到答案。

假设我有一个源文件main.c

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

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

这样做,我能够访问struct的数组,但是这个方法不被认为是taboo,因为我的person数组是一个全局变量?

然后我尝试将数组初始化移动到主函数中

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

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

这样做,当我到达addName()函数时,我得到一个'person unclared'错误。如何在不使其成为全局变量的情况下访问其函数之外的person []数组?提前感谢您的帮助。下面我有必要的示例data.h。

data.h

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

2 个答案:

答案 0 :(得分:2)

只需将参数传递给addName()函数。

实施例

#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);
}

答案 1 :(得分:0)

是的,在这种情况下传递变量,人。

person是struct newPerson的数组。

将数组作为参数传递,你应该像这样定义函数

//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
    //...
}
相关问题