簡體   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