我试图将带有新字符串的字符串数组传递给函数,并且在此函数内部,我想将此字符串添加到数组中并重置该字符串。我似乎无法使其在函数内部起作用,但是没有它可以起作用
int main(void)
{
const char* text = "hello world";
int text_length = strlen(text);
char* words[text_length];
char word[text_length];
int length = 0;
int k = 0;
for (int i = 0; i < text_length; ++i) {
if (isspace(text[i])) {
words[length] = malloc(strlen(word) + 1);
strcpy(words[length++], word);
memset(word, 0, sizeof(word));
k = 0;
}
//...
//... adding chars to the word
word[k++]= text[i];
}
}
这工作正常,但没有:
void add_word(char* words[], char* word, int* words_length, int* word_cursor)
{
words[*words_length] = malloc(strlen(word) + 1);
strcpy(words[*words_length++], word);
memset(word, 0, sizeof(word));
*word_cursor = 0;
}
int main(void)
{
const char* text = "hello world";
int text_length = strlen(text);
char* words[text_length];
char word[text_length];
int length = 0;
int k = 0;
for (int i = 0; i < text_length; ++i) {
if (isspace(text[i])) {
add_word(words, word, &length, &k);
}
//...
//... adding chars to the word
word[k++]= text[i];
}
}
我想念什么?
答案 0 :(得分:1)
您的
行为不确定double > & values (Array<) – (Array<double>) The values at the point.
Array< double > & x (const) – (Array<double>) The coordinates of the point.
ufc::cell & cell (const) – (ufc::cell) The cell which contains the given point.
因此,void add_word(char* words[], char* word, int* words_length, int* word_cursor) {
strcpy(words[*words_length++], word);
不包含用于容纳word
char的空间。
null
应该是
const char* text = "hello world";
int text_length = strlen(text);
char word[text_length];
和
char word[text_length+1];
答案 1 :(得分:1)
我的 猜测 是,它不起作用,因为您没有在word
数组中正确添加空终止符。
在第二个示例中,您只是从第一个工作代码中复制粘贴了代码,而忘记更改一个关键位:
memset(word, 0, sizeof(word));
在函数add_word
中,变量word
是 pointer ,而sizeof(word)
返回指针本身的大小,而不是指针指向的大小。 / p>
确保word
中的字符串始终以空值结尾的最佳解决方案是在要将其视为字符串时,在所需位置实际并显式添加终结符:
if (isspace(text[i])) {
word[k] = '\0'; // Add null-terminator
add_word(words, word, &length, &k);
}