如何使用结构数组c

时间:2014-07-11 22:22:38

标签: c arrays struct

我有一个问题......我如何使用结构数组?我设法创建它,但是我不能在scanf和printf中使用它......我将在这里只发布我需要的部分代码...

主要功能是:

int main()
{
    int r;
    struct word *s;
    s=(struct word*)malloc(sizeof(struct word));
    struct word hashtable[100];
    s->name=(char*)malloc(20*sizeof(char));
    scanf("%s",s->name);
    r=hashnumber(s->name);
    char *name="example.txt";
    if(hashtable[r]->name==NULL)
        treecreation(&hashtable[r],s);
    else
        hashtable[r]=s;
    printf("%s",hashtable[r]->name);
    printresults();
    system("pause");
    return(0);
}

struct word是:

struct position
{
    char *filename;
    int line;
    int place;
    struct position *next;
};

struct word
{
    char *name;
    struct word *right;
    struct word *left;
    struct position *result;
};

功能树创建就像:

void treecreation(struct word **w1,struct word *w2)

不要打扰我的其余功能......我相信它们有效...主要问题是如何使用那个结构数组......现在,我的程序没有编译,因为“如果“声明,”树形“和printf ..我该怎么办?任何帮助将不胜感激......

3 个答案:

答案 0 :(得分:3)

您的程序未编译因为您的变量hashtable类型错误。

您希望在其中存储ss是指向单词的指针。因此,hashtable必须是指向word的指针数组:

struct word *hashtable[100];

现在,当你致电treecreate时,你只需传递一句话:

treecreation(hashtable,s);

答案 1 :(得分:0)

hashtable[r]的类型为struct word&hashtable[r]的类型为struct word*。这就解释了为什么你不应该使用&hashtable[r]作为treecreation的参数。

您需要传递给treecreation的内容取决于您在函数中使用参数w1所做的事情。

如果您要分配内存并分配给*w1,那么您需要使用:

struct word* hashtable;
treecreation(&hashtable, s);

答案 2 :(得分:0)

->运算符用于通过指向该结构的指针从结构中选择一个字段。 hashtable[r]是一个结构,而不是指向一个结构的指针。您可以使用普通的.运算符来选择成员,就像您使用标量struct word(您是)一样:

if (hashtable[r].name == NULL) {
    ...