2

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...

3 Answers 3

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

You probably meant treecreation(hashtable,s);
0

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) {
    ...

1 Comment

Well,I used struct word *hashtable[100]; and now it compiles...!Thanks a lot!
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.