0

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?

4
  • 1
    What problem you are facing? Can you be more specific? Commented Mar 31, 2017 at 9:54
  • 1
    Please paste your complete code. Commented Mar 31, 2017 at 9:55
  • In addition to the answer(s) below: consider what is going to happen to itemValue if findItem returns NULL. Commented Mar 31, 2017 at 10:15
  • i can not post the code because it is part of socket programming assignment and if someone copied the same code i will get zero mark Commented Mar 31, 2017 at 12:00

1 Answer 1

4

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

5 Comments

yes i did the same and it worked + also i removed &key and pass key only .. it now executed but i always get an empty value from search_items
Well, does your string exist? The code has been properly corrected. Now it is up to you to either show more code, what key is or similar.
how can i access to the memory to check weather the struct is stored correctly or not ?
I don't know what exactly you want to do so I don't have an answer.
using gdb debugger solved my issue .. apperently i was not saving the struct using memcpy command and i was losing my data.

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.