gpt4 book ai didi

c - 根据分隔符将单词附加到数组

转载 作者:太空宇宙 更新时间:2023-11-04 04:58:42 25 4
gpt4 key购买 nike

我正在尝试将“once upon a time”这句话分解成一系列单词。我通过 for 循环执行此操作,检测三个条件:

  • 这是循环的结尾(添加\0 并中断);
  • 是分隔符(加\0前进到下一个字)
  • 其他任何东西(添加字符)

这是我现在拥有的:

#include <stdlib.h>
#include <stdio.h>

char ** split_string(char * string, char sep) {
// Allow single separators only for now

// get length of the split string array
int i, c, array_length = 0;

for (int i=0; (c=string[i]) != 0; i++)
if (c == sep) array_length ++;

// allocate the array
char ** array_of_words = malloc(array_length + 1);
char word[100];

for (int i=0, char_num=0, word_num=0;; i++) {

c = string[i];

// if a newline add the word and break
if (c == '\0') {
word[char_num] = '\0';
array_of_words[word_num] = word;
break;
}

// if the separator, add a NUL, increment the word_num, and reset the character counter
if (c == sep) {
word[char_num] = '\0';
array_of_words[word_num] = word;
word_num ++;
char_num = 0;
}

// otherwise, just add the character in the string and increment the character counter
else {
word[char_num] = c;
char_num ++;
}
}

return array_of_words;

}
int main(int argc, char *argv[]) {


char * input_string = "Once upon a time";

// separate the string into a list of tokens separated by the separator
char ** array_of_words;
array_of_words = split_string(input_string, ' ');
printf("The array of words is: ");

// how to get the size of this array? sizeof(array_of_words) / sizeof(array_of_words[0]) gives 1?!
for (int i=0; i < 4 ;i++)
printf("%s[sep]%d", array_of_words[i], i);

return 0;

}

但是,它不是在最后打印“once”、“upon”、“a”、“time”,而是打印“time”、“time”、“time”、“time”。

导致此问题的代码错误在哪里?

这是代码的一个工作示例:https://onlinegdb.com/S1ss6a4Ur

最佳答案

您需要为每个单词分配内存,而不仅仅是一个。 char word[100];只为一个单词预留内存,一旦超出范围,内存就失效了。相反,您可以动态分配内存:

char* word = malloc(100);

然后,当你找到一个分隔符时,为一个新词分配内存:

if (c == sep) {
word[char_num] = '\0';
array_of_words[word_num] = word;
word = malloc(100);

另外,这里是不正确的:

char ** array_of_words = malloc(array_length + 1);

您需要为所有 char 指针分配足够的内存,但您仅为每个指针分配 1 字节。相反,这样做:

char ** array_of_words = malloc(sizeof(char*)*(array_length + 1));

array_of_words 是一个数组时,sizeof(array_of_words)/sizeof(array_of_words[0]) 用于计算元素的数量,因为那时它的大小是已知的编译时间(除了 VLA)。它只是一个指针,所以它不起作用,因为 sizeof(array_of_words) 会给你指针大小。相反,您必须自己计算尺寸。您已经在 split_string 函数中这样做了,所以您只需要将 array_of_words 输出到 main 函数中。有多种方法可以做到这一点:

  • 让它成为一个全局变量
  • int* 传递给函数,通过它您可以将值写入 main 中的变量(这有时称为“输出参数”)
  • 通过将它们包装在 struct
  • 中,将其与您要返回的其他指针一起返回
  • 根本不传,重新计算

对于这个小程序,全局变量的解决方案是最简单的,只需将int array_length = 0;放在split_string之前,而不是放在里面。


最后但同样重要的是,由于我们使用了 malloc 来分配内存,我们应该释放它:

for (int i = 0; i < array_length; i++) {
printf("%s[sep]%d", array_of_words[i], i);
free(array_of_words[i]); // free each word
}
free(array_of_words); // free the array holding the pointers to the words

关于c - 根据分隔符将单词附加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57865248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com