[英]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.