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

How to set index of char pointer array to a char pointer?

我用逗号标记,这让我在 while 循环中得到 char * 作为输出。如何将 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]);
 }

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

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

我将你的 C "pseudo-code" 修改为一个工作程序。

#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。这是未定义的行为,我已经更正了代码。