繁体   English   中英

如何使用结构体数组c

[英]how to use array of structs c

我有一个问题...如何使用结构数组?我设法创建了它,但是我不能在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 position
{
    char *filename;
    int line;
    int place;
    struct position *next;
};

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

函数treecreation就像:

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

不要打扰我的其余功能...我相信它们会起作用...主要问题是如何使用该结构数组...目前,由于“ if”语句,我的程序无法编译,“ treecreation”和printf ..我该怎么办?任何帮助将不胜感激...

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

要存储s在里面。 s是单词的指针。 因此,您的hashtable必须是一个指向单词的指针数组:

struct word *hashtable[100];

现在,当您调用treecreate您只需要输入单词:

treecreation(hashtable,s);

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

需要传递给treecreation取决于函数中对参数w1的处理方式。

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

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

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

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

暂无
暂无

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

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