LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

string array as function parameter fails in loop

Solved!
Go to solution

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!

0 Kudos
Message 1 of 3
(3,752 Views)
Solution
Accepted by topic author ZerMahlMeer

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

Message 2 of 3
(3,733 Views)

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!

0 Kudos
Message 3 of 3
(3,655 Views)