我有一个单词句子,我正在尝试遍历这个句子,将每个单独的单词存储到动态分配的内存中,然后将指向每个单词的指针存储在指针数组中。
我很困惑如何在内存中创建新的空间,然后将数据复制到下一个更大的阵列中
char** str_to_arr_words (char *str) {
int length;
char** arr_words;
int numOfWords;
//Loop until you've reached the end of the sentence
while(*str != 'n'){
//loop until you reach the end of a word
while(*str != ' '){
length++;
str++;
}
//allocate space in memory for the word
char* word = malloc(length);
//set str back to the start of the word
str = str - length;
//copy the word in the sentence into its own position in memory
for(int x = 0; x < length; x++){
word[x] = str[x];
}
numOfWords++;
//increse the size of the array of word addresses by one and put the most recent address in the new array
char** newArrWords = malloc(numOfWords);
for(int x = 0; x < numOfWords - 1; x++){
newArrWords[x] = arr_words[x];
}
newArrWords[numOfWords] = str;
//set str back to the start of the next word (+1 to skip the ' ')
str = str + length + 1;
length = 0;
}
}
首先,函数无法从这些while(*str != 'n')
和while(*str != ' ')
语句中转义,因为当我向该函数发送字符串时,它会找到字符串的末尾,但随后会在字符串的末尾添加无意义字符,因此上*str != 'n'
条件永远不会为假。然后循环再次进入内部,由于这些非意义的字符,内部条件也总是真的。所以我把它修好了;
while((*str != 'n') && (*str != NULL)){
//loop until you reach the end of a word
while ((*str != ' ') && (*str != 'n') ) {
length++;
str++;
}
...
你没有初始化arr_words
,老实说,我不明白这个数组应该做什么,但我只是把字符串复制到它里面;
char* arr_words = (char *)malloc(length);
strcpy(arr_words, word);
我认为使用strcpy
而不是循环是一个更好的选择。我也为newArrWords
做了同样的事情。您可以对其进行修改;
char* newArrWords = (char *)malloc(numOfWords);
strcpy(newArrWords, str);