简体   繁体   English

char指针的多维数组

[英]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. j当然是行,每次添加都会增加。

The result must be an array that, for every row, contains two columns, one whit an ingredient, and another with the relative strMix. 结果必须是一个数组,该数组的每一行都包含两列,一列包含一种成分,另一列包含相对的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. 精确地,它为每行读取最后读取的strMix。

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上,而从来没有出现在elements [i]字符串上。

strMix column is correct only if I write it inside listA, and immediately read it. 仅当我将它写入listA并立即读取时,strMix列才是正确的。 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. 对于每个j,它们都是相同的,等于最后读取的strMix。

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. 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. 使用存储字符串的char数组。 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. 使用将字符串存储地址的char *数组, 为每个引用的字符串分配单独的内存。

Regardless, to copy the strings, prefer strncpy() to the unsafe strcpy() . 无论如何,要复制字符串,请将strncpy()为不安全的strcpy()

Is it C or C++? 是C还是C ++? Maybe instead of using the assignment: 也许不用分配:

listA[j][0]=strMix;

you should use strcpy function? 您应该使用strcpy函数吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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