简体   繁体   English

在声明中迭代没有大小的结构数组

[英]Iterating over array of structs without size in declaration

I've been having problems with trying to iterate over array of structs.我一直在尝试迭代结构数组时遇到问题。 The setup is as following:设置如下:

data.h数据.h

typedef struct data {
    char *name;
    char *age;
} data;
data array_of_data[];

data.c数据.c

data array_of_data[4] = {
    {"John", "24"},
    {"Melissa", "32"},
    {"Ludwing", "98"}
};

main.c main.c

#include "data.h"
int main() {
    int i=0;
    while(&array_of_data[i] != NULL) {
        do_something();
        i++;
    }
    return 0;    
}

I can't have number of elements in declaration in.h file.我在.h 文件中的声明中不能包含多个元素。 So iterating with for loop and sizeof, or while loop doesn't work.因此使用 for 循环和 sizeof 或 while 循环进行迭代是行不通的。 With my solution I'm getting an 'undefined reference' error.使用我的解决方案,我收到“未定义的引用”错误。 I don't understand why.我不明白为什么。 Any help is appreciated.任何帮助表示赞赏。

One of the simplest ways to process an array without giving its length is to use a guard value, for example NULL as last value.处理数组而不给出其长度的最简单方法之一是使用保护值,例如NULL作为最后一个值。

This would result in code like this:这将导致如下代码:

data array_of_data[4] = {
    {"John", "24"},
    {"Melissa", "32"},
    {"Ludwing", "98"},
    {NULL, NULL},
};

int main() {
    int i=0;
    while(array_of_data[i].name != NULL) {
        printf("[%d] %s, %s\n", i, array_of_data[i].name, array_of_data[i].age);
        i++;    
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM