c - 将来自标准输入的输入存储在 C 中的数组中

标签 c arrays

我正在使用以下代码将标准输入存储到一个数组中。我最终收到大量警告和段错误。

while(fgets(str, 256, stdin)){

        size_t count = 0;
        char** arr = NULL;
        char* token = NULL;
        char* delim = ' ';

        for(int i=0; i < strlen(str); i++) 
            if (isspace(str[i])) count++;

        count++;
        arr = malloc(sizeof(char*) * (count));

        for(int i=0; i <= count; i++){

            token = strtok(str, delim);
            arr[i] = token;
        }

        for (int i = 0; i < count; ++i)
        {
            printf("%s\n", arr[i]);
        }

        //if(strncasecmp(str, "quit", 4) == 0) break;


        free(arr);

    }

我对编译中的这个警告有点困惑

c:34:12: warning: incompatible integer to pointer conversion initializing 'char *' with an expression of type 'int'
      [-Wint-conversion]
        char* delim = ' ';
              ^       ~~~

当然,最后当我运行它时,我遇到了段错误。

admin 123 tyu
Segmentation fault: 11

我在这里做错了什么。

最佳答案

我在这里注意到第一个问题。 这可不好。

   for(int i=0; i <= count; i++){

        token = strtok(str, delim);
        arr[i] = token;
    }

将其替换为以下内容:

    token = strtok(str, delim);
    while(token){
        arr[i] = token;
        token = strtok(NULL, delim);
    }

strtok 的引用手册说你在str 上使用它一次,其余使用NULL 连续分割字符串。看strtok()手册页和给定的简单用法示例。

第二点是 delim 必须是 C 字符串,所以在您的情况下 char* 类型将是 delim = "" 不是 delim = ' '。理想情况下,它也应该是 const char *delim = "";

关于c - 将来自标准输入的输入存储在 C 中的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30429585/

相关文章:

arrays - IsInArray 在应该返回 True 时没有返回

java - 如何将纬度/经度列表转换为字符串数组?

c - 从 .txt 文件读取到 C 数组中?

c - 逐行读取直到找到整数 C

c - 如何在c中加载ogg文件?

在 C 中将 int 转换为 short

arrays - 在 Swift 2 中定义不可变字典数组的优雅方式是什么?

c - 如何在运行时在 C 中存储多个字符串数组?

c - 如果我声明一个参数表为空的函数,然后将参数传递给它会怎样?

c - stdin 上的 read() 返回 EOF 而不是等待输入