LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

Initialization of character arrays - problem

I've encountered an anomaly in the behavior of CVI when initializing character arrays in a function like this:

char *tab[] = { "abc", "klm", "xyz" };

The problem is that if this local array is changed, the next time the function is called those changes have stuck, rather than being re-set to the initialization values.

A very simple example program (35 lines) is attached.

Obviously, an easy work-around is to properly first declare and then initialize the array -- much better style -- and I will be doing so from now on.

Hopefully this post will warn others, and prompt an update to the compiler if this is in fact not proper C behavior.

--Ian
0 Kudos
Message 1 of 3
(3,217 Views)
The behavior you are seeing is in fact the correct behavior. The reason is, you are not actually allocating any stack space to store the three string values; instead, you are just allocating an array of pointers to them, which then point into the data segment of your program, where those strings only exist once. What you probably want is to declare space on the stack for them so a local copy is made of the values so they are initialized to the same thing every time.


char tab[][4] = { "abc", "klm", "xyz" };


Doing it this way will produce the result you expect.

As a side note, some compilers will place static strings ("abc", etc.) into read only memory (if available) and your program would crash. Therefore, doing it the second way not only produces the desired result, it is safer for cross-platform development.

Hope this helps,

Alex
Message 2 of 3
(3,210 Views)
Ah ha! Thanks for the clear explanation.
0 Kudos
Message 3 of 3
(3,203 Views)