填充动态分配的字符串数组? [英] populating dynamically allocated array of strings?
问题描述
我有以下代码来填充字符串数组,但是每次更改值时,整个数组都会更改(而不是单个字符串)
I have the following code to populate an array of strings, but every time i change the value, the entire array changes (instead of a single string the array)
推荐答案
这是因为对于数组的所有位置,您都是指向char的同一指针.
That's because you are the same pointer to char for all positions of the array.
当您这样做:
words[i] = txt;
您正在分配一个指针.因此,每个word[i]
都是相同的字符串(txt
).
如果您真的想将单词读入缓冲区(如txt
),然后将其放入字符串数组,则需要将缓冲区字符串的内容复制到数组中的字符串,如下所示:
You are assigning a pointer. So every single word[i]
is the same string (txt
).
If you really want to read the word into a buffer (like txt
) and then put it into the array of strings, you need to copy the contents of the buffer string to the string in the array, like so:
strncpy(words[i], txt, MAX_WORD_LENGTH);
您的代码还有另一个问题,那就是字符串数组的分配. 应该是:
There's also another problem with your code, which is the allocation of the string array. It should be:
words = (char**)malloc(wordcount * sizeof(char*));
这是因为字符串数组是指向char指针(char**
)的指针,并且数组的每个元素都是字符串(char*
).现在您已经分配了一个char指针数组,但是还没有为每个字符串分配内存,这是我们接下来要做的:
That is because a string array is a pointer to a char pointer (char**
), and each element of the array is a string (char*
). Now you have allocated a array of char pointers, but you have not allocated the memory for each string, which is what we do next:
for (i = 0; i < wordcount; i++) {
words[i] = (char*)malloc(MAX_WORD_LENGTH * sizeof(char));
}
如果您不想使用缓冲区而直接读入字符串数组,则代码将是这样的:
If you want to not use a buffer and read directly into the string array, your code would be something like this:
words = (char**)malloc(wordcount * sizeof(char*));
input = fopen(filename, "r");
while(!feof(input)) {
words[i] = (char*)malloc(MAX_WORD_LENGTH * sizeof(char));
fscanf(input, "%s", words[i]);
}
这篇关于填充动态分配的字符串数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!