【问题标题】:how to use array of structs c如何使用结构数组c
【发布时间】:2014-07-12 11:11:55
【问题描述】:

我有一个问题...如何使用结构数组?我设法创建了它,但我无法在 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;
};

而函数树创建是这样的:

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

不要打扰我的其他功能...我相信它们可以工作...主要问题是如何使用该结构数组...现在,我的程序无法编译,因为“ if”语句,“treecreation”和printf ..我该怎么办?任何帮助将不胜感激...

【问题讨论】:

    标签: c arrays struct


    【解决方案1】:

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

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

    struct word *hashtable[100];
    

    现在,当您拨打treecreate 时,您只需传递单词:

    treecreation(hashtable,s);
    

    【讨论】:

    • 你的意思可能是treecreation(hashtable,s);
    【解决方案2】:

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

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

    【讨论】:

    • 好吧,我用了struct word *hashtable[100];现在它编译...!非常感谢!
    【解决方案3】:

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

    您需要传递给treecreation 的内容取决于您对函数中的参数w1 执行的操作。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-22
      • 1970-01-01
      • 1970-01-01
      • 2011-01-22
      • 2018-09-21
      • 2015-12-18
      • 1970-01-01
      相关资源
      最近更新 更多