简体   繁体   中英

Multidimensional array of char pointer

Good day to everyone,

there's some kind of big deal that I cannot figure out. I create a multidimensional array of pointers:

char *listA[5000][2];

In particular condition, I want that specific strings are saved inside this array. These are a normal string, in a simple variable, and another contained inside an array of strings.

 listA[j][0]=strMix;
 listA[j][1]=ingredients[i];
 j++;

j , of course, is the row, that is increased for every adding.

The result must be an array that, for every row, contains two columns, one whit an ingredient, and another with the relative strMix.

The problem is that when I try to read this multidimensional array:

printf( "%s", listA[0][1]); // the ingredient

is always correct, but:

printf( "%s", listA[0][0]); // the strMix code

is always incorrect; precisely it reads the last strMix read, for every row.

I tried to change the order of the columns, and with my big surprise, the problem is always for the strMix, and never for the ingredients[i] string.

strMix column is correct only if I write it inside listA, and immediately read it. Of course, I'd say.

For example:

printf("Current: %s vs Previously: %s",lista[j][0], lista[j-1][0]);

they are the same, for every j, equal to the last strMix read.

If you have any ideas, something about memory or multidimensional array of pointers that I simply are missing, I'd appreciate your advises.

Thank you for the time, in every case. fdt.

You're not saving strings in this array -- you're saving pointers.

This statement copies an address, not a string:

 listA[j][0]=strMix;

If you want to copy the string, you can either:

  • Use an char array that stores the strings. For some strings, this may use too much memory. For others, it may offer not enough.
  • Use a char* array that stores addresses to the strings, and allocate separate memory for each referenced string.

Regardless, to copy the strings, prefer strncpy() to the unsafe strcpy() .

Is it C or C++? Maybe instead of using the assignment:

listA[j][0]=strMix;

you should use strcpy function?

strcpy (listA[j][0], strMix);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM