简体   繁体   English

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

[英]How to set index of char pointer array to a char pointer?

I'm tokenizing by commas, which gives me char * as an output in a while loop. 我用逗号标记,这给我char *作为while循环中的输出。 How do I assign each of these char pointers in the while loop to the index of a char pointer []? 我如何在while循环中将每个这些char指针分配给char指针[]的索引?

Pseudocode: 伪代码:

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++;
}

Error: I print out the value of p and after printing index 0, it fails. 错误:我打印出p的值,并且在打印索引0后失败。 Here is my code for printing it out: 这是我的打印代码:

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

Here is my error: "0 g" when my input is "gmn" and it prints out Segmentation fault: 11. 这是我的错误:当我的输入为“ gmn”时,错误为“ 0 g”并打印出细分错误:11。

Your program is mostly correct, but I think your problem is that you're using strtok() incorrectly. 您的程序大部分是正确的,但是我认为您的问题是您使用的strtok()错误。 Upon its first call, strtok() expects a string and delimiters. 首次调用时, strtok()需要一个字符串和定界符。 Subsequent calls expect NULL and delimiters. 后续调用期望使用NULL和定界符。

I modified your C "pseudo-code" to a working program. 我将您的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]);
    }
}

Edit: I just realized that my original code used an uninitialized pointer p . 编辑:我刚刚意识到我的原始代码使用了未初始化的指针p This is undefined behavior, and I have corrected the code. 这是未定义的行为,我已经更正了代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM