我是C新学员。我对这个下面的代码感到困惑,它的目标是打印结构数组中的所有元素。我知道它可以直接在main()中完成,但是当我将printf(....)放入一个函数并调用此函数时,我无法传递结构数组。 有人知道为什么。我很不高兴..谢谢如何将结构数组传递给C中的函数?
我的结构包括关键字和它的数量。初始化包含常量集的名称和它的计数为0。
#include <stdio.h>
#include <stddef.h>
#define NKEYS (sizeof keytab/ sizeof (Key))
void traversal(Key tab[], int n); // define the function
struct key // create the structure
{ char *word;
int count;
};
typedef struct key Key; //define struct key as Key
Key keytab[]={ // initiate the struct array
"auto",0,
"break",0,
"case",0,
"char",0,
"const",0,
"continue",0,
"default",0,
"void",0,
"while",0,
};
int main()
{
traversal(keytab,NKEYS);
return 0;
}
void traversal(Key tab[], int n){
int i;
for (i=0; i<n; i++){
printf("%s\n",keytab[i].word);
}
}
初始化不应该起作用。你有一个'struct'数组,所以你需要嵌套大括号。对于函数也使用原型声明器,'#define'在最好情况下是危险的(使用类型的名称作为参数;不要硬编码名称,这是灾难的原因)。 – Olaf
'struct key {...}'和'typedef struct key key;'移动到顶部(之前.'void遍历(Key tab [],int n);') – BLUEPIXY
当然:“我没有通过结构数组“不是特定的**问题描述。 – Olaf