简体   繁体   中英

how to use array of structs c

I have a question...How can I use an array of structs?I managed to create it,but I cannot use it in scanf and printf...I will post here only the part of my code that is necessary...

The main function is:

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 is:

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

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

And function treecreation is like:

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

Do not bother with the rest of my functions...I believe that they work...The main problem is how to use that array of structs...Right now,my program does not compile,because of the "if" statement,the "treecreation" and the printf..What should I do?Any help would be appreciated...

Your program is not compiling beause your variable hashtable has the wrong type.

You want to store s in it. s is a pointer to word. Therefore, you hashtable has to be an array of pointers to word:

struct word *hashtable[100];

Now, when you call treecreate you just need to pass the word:

treecreation(hashtable,s);

The type of hashtable[r] is struct word . The type of &hashtable[r] is struct word* . That explains why you should not use &hashtable[r] as an argument to treecreation .

What you need to pass to treecreation depends on what you are doing with the argument w1 in the function.

If you are allocating memory and assigning to *w1 , then, you need to use:

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

The -> operator is for selecting a field from a struct via a pointer to that struct. hashtable[r] is a struct, not a pointer to one. You use the ordinary . operator to select a member, just as if you were operating on a scalar struct word (which you are):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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