c - 如何将 char 指针数组的索引设置为 char 指针?

标签 c arrays pointers char token

我用逗号进行标记,这给了我 char * 作为 while 循环中的输出。如何将 while 循环中的每个 char 指针分配给 char 指针 [] 的索引?

伪代码:

char * p;
char * args[30];
int i = 0;
while(p!=NULL){
    p = strtok(NULL,",");
    args[i] = p; //attempt 1
    *(args + i) = p; //attempt 2
    strcpy(p,args[i]); //attempt 3
    i++;
}

错误: 我打印出 p 的值,在打印索引 0 后,它失败了。这是我的打印代码:

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

这是我的错误: 当我输入“g m n”并打印出“0 g”时 段错误:11。

最佳答案

您的程序大部分是正确的,但我认为您的问题是您错误地使用了 strtok() 。第一次调用时,strtok() 需要一个字符串和分隔符。后续调用需要 NULL 和分隔符。

我将您的 C“伪代码”修改为工作程序。

#include <stdio.h>
#include <string.h>

void main(int argc, char* argv[]) {
    char* p;
    char* args[30];
    int i = 0;
    int j;

    char input[30];
    puts("Please enter a string:");
    scanf("%29s", &input); /* get a string to break up */

    p = args[i++] = strtok(input, ",");  /* first call to strtok() requires the input */

    while(p!=NULL && i < 30) { /* added bounds check to avoid buffer overruns */
        p = strtok(NULL,","); /* subsequent calls expect NULL */
        args[i] = p; /* this is the best way to assign values to args, but it's equivalent to your attempt 2*/
        i++;
    }

    for(j = 0; j < i; j++){
            printf("%s \n",args[j]);
    }
}
<小时/>

编辑:我刚刚意识到我的原始代码使用了未初始化的指针p。这是未定义的行为,我已经更正了代码。

关于c - 如何将 char 指针数组的索引设置为 char 指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32672445/

相关文章:

c - 如果在 C 结构中定义

c++ - OpenMP,for 循环内部部分

objective-c - Objective-C 运行时性能惩罚的细节

arrays - 如何在golang中gzip字符串并返回字节数组

c++ - 链表中节点赋值的概念意义

c 将 int* 类型的指针转​​换为 char*,然后访问该值

c - 如何实现动态字符串矩阵?

JavaScript 随机报价生成器

c - 使用 const 成员将结构转换为结构

Java:动态调整二维数组中列的大小