Rabab Alkhalifa
Rabab Alkhalifa

Reputation: 95

Return structure pointer in C

Could you please help me in correcting my code:

This is a function that returns a pointer to struct item:

struct item* findItem(const char* key) {
    for (int i = 0; i < nItems; i++) {
        if (!strcmp(items[i].key, key)) { return &items[i]; }
    }
    return NULL;
}

From main function, I want to retrieve my struct value as following:

struct item search_items = findItem(&key) ; // I have problem with this line 
char* itemValue;
if (search_items != NULL)
{
    itemValue = search_items->value;
}

How can I retrieve the structure and save it to be used in the main function?

Upvotes: 0

Views: 578

Answers (1)

unalignedmemoryaccess
unalignedmemoryaccess

Reputation: 7441

If you are returning pointer from function, then you have to read it as pointer. Notice struct item* search_items part on my code and on your (I added pointer *)

struct item* search_items = findItem(&key) ; // i have problem with this line 
char* itemValue;
if ( search_items != NULL)
{
    itemValue = search_items->value;
}

Upvotes: 4

Related Questions