2015-12-09 101 views
-2

我是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); 
    } 
} 
+2

初始化不应该起作用。你有一个'struct'数组,所以你需要嵌套大括号。对于函数也使用原型声明器,'#define'在最好情况下是危险的(使用类型的名称作为参数;不要硬编码名称,这是灾难的原因)。 – Olaf

+3

'struct key {...}'和'typedef struct key key;'移动到顶部(之前.'void遍历(Key tab [],int n);') – BLUEPIXY

+0

当然:“我没有通过结构数组“不是特定的**问题描述。 – Olaf

回答

1

声明任何结构或功能的使用它,而不是之后

#include <stdio.h> 
#include <stddef.h> 
#define NKEYS (sizeof keytab/ sizeof (Key)) 

// define struct first 
struct key      // create the structure 
{ char *word; 
    int count; 
}; 
typedef struct key Key; 

//then the functions that uses it 
void traversal(Key *tab, int n); 


Key keytab[]={ 
    "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",tab[i].word); 
    } 
} 
1

traversal功能之前,你有一个说法称为tab,但您实际上并未使用该参数。相反,您直接使用keytab。因此,即使您传递了其他内容,该函数也会始终打印keytab

此外,您可以通过使用sentinel value来标记数组的末尾来避免计算/传递数组的大小。当结构包含指针时,值NULL可用作良好的哨兵,例如, word

#include <stdio.h> 
#include <stddef.h> 

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 }, 
    { NULL,0 }    // sentinel value to mark the end of the array 
}; 

void traversal(Key tab[]){ 
    int i; 
    for (i=0; tab[i].word != NULL; i++){ 
     printf("%s\n",keytab[i].word); 
    } 
} 

int main(void) 
{ 
    traversal(keytab); 
    return 0; 
}