01-21-2016 11:09 AM
Hallo,
I've got a weird issue here and I hope some one can help me finding the cause.
I have a function where I declared an array of strings (string_list). I pass the array to a function that does modifactions to the array. Whenn I address the string array index by index all values are stored properly. When I loop through the array incrementing the index automatically only the last index value will be stored in ALL positions.
Why is that? Or what am I doing wrong?
//this is the passing a string array to another function int calling_function { char *string_list[MAX_PATHNAME_LEN]; //< store strings in here function_called( string_list ); // passing a pointer to a string array return 0; } // this is the function receiving a reference to a string array to store data int function_called( char* output_list[] ) {
int i = 0; // counter variable /*This works and the right values are stored in output_list*/ output_list[0] = "02"; output_list[1] = "12"; output_list[2] = "22"; output_list[3] = "32"; output_list[4] = "42"; output_list[5] = "52"; output_list[6] = "622"; output_list[7] = "72"; /*this does not work and will store '31' in all places of the array*/ while( i < 32 ) { Fmt( sample, "%s<%d", i ); // increment value output_list[ i ] = sample; // store value in index i = i ++; // increment counter } }
Thanks!
Solved! Go to Solution.
01-22-2016 01:51 AM
Hi,
When you do
output_list[ i ] = sample;
all of the members of the array have the same value: sample-a char pointer. You are afterwards modifying the contents of sample but the previous values still point to sample.
If you assign values to each array member like:
output_list[0] = "02"; output_list[1] = "12"; ...
you assign different values: a pointer to a string containing "02", a pointer to a string contaning "12", ...
If you want to assign values in a loop you need to allocate memory for each string(output_list[i]) and copy the contents of sample in them.
Does this make sense to you?
Constantin
01-28-2016 09:25 AM - edited 01-28-2016 09:30 AM
That makes somewhat sense! Thanks for your answer!
Edit: My summary .. your answer became 100% clear seconds after I replied!
So what I did was assigning the same pointer (a char array named sample) to all elements of output_list. All elements pointed to the same direction in memory. When changing that memory location (sample) of course I changed all elements!