user3435894
user3435894

Reputation: 117

Unable to assign values in a structure

I have declared the structure:

typedef struct keyValuePairs{
char* type;
char* key;
char* valueType;
char* value;
} keyValueType;

keyValueType keyValuePairs[1000];

And in a function declared the local variables as:

char key[500];
char value[500];

to hold the key value pair values as:

key[i]="abc";
value[i]="xyz"

I have assigned these local variables to the global variable as:

keyValuepairs[1].key=key.

Once i come out of the function, the values assigned in the structure is getting lost. Can someone explain where I am going wrong? Please note I am fairly new to C.

Upvotes: 0

Views: 84

Answers (3)

Adrian
Adrian

Reputation: 713

You have not allocated memory for type, key, valueType and value. Try static memory allocation :

typedef struct keyValuePairs{
char* type[n];
char* key[n];
char* valueType[n];
char* value[n];
} 

Where n is a defined constant

Upvotes: 0

R Sahu
R Sahu

Reputation: 206607

If I understand you correctly, you are trying something along the lines of:

typedef struct
{
   char* val;
} A;

A alist[10];

void foo()
{
   char t[10];
   t = "abc";
   alist[0].val = t;
}

int main()
{
   foo();
}

First of all, the line

t = "abc";

is syntactically incorrect. You have to use something like:

strcpy(t, "abc");

But the most important error is that when you return from foo, alist[0].val points to an address that is not good any more. To make sure alist[0].val points to a valid address, you have to allocate memory from the heap for it and copy the contents of t to it.

void foo()
{
   char t[10];
   strcpy(t,"abc");
   alist[0].val = malloc(strlen(t)+1);
   strcpy(alist[0].val, t);
}

To do a thorough job, you'll have to make sure that you call free on that allocated memory at some point before you return from main.

Upvotes: 1

Begelfor
Begelfor

Reputation: 358

Both key and value variables are pointers to arrays that are allocated in the stack when you are in the function. After keyValuepairs[1].key=key the global variable points to that same place in the stack. After exiting the function, the memory where those arrays were is reused.

I suggest you read up on static vs dynamic allocation in C

Upvotes: 1

Related Questions