C 将字符串拆分为单个单词并将单个单词保存在数组中

标签 c pointers

假设用户输入“程序一二三”。我将其保存在 userTyped 数组中并将其传递给 parse() 函数。我需要 parse() 函数来实现

userargv[0]是程序

userargv[1] 是一个

userargv[2] 是二

等等

我可以看出它一定是涉及指针的东西,但我无法弄清楚。代码如下:

int main(int argc, char **argv)
{
char userTyped[1000];

char* userargv[100];//this is where i need the parse() function to store the arguments to pass to execv

printf("typesomething>");

fgets(userTyped, 1000, stdin);

parse(userTyped, &userargv);

return 0;
}



int parse(char* userTyped, char* userargv){

const char whitespace[2] = " "; //the deliminator
char *strings;

strings = strtok(userTyped, whitespace);

while( strings != NULL )
{
    strings = strtok(NULL, whitespace);

 }
//THIS ALL WORKS, BUT I NEED TO DO SOMETHING LIKE userargv[i] = strings;
//OR *userargv[i] = &strings;
//OR SOMETHING LIKE THAT.

return 0;
}

最佳答案

您必须分配一个字符串数组(char**),并分配它的每个元素,然后将所有找到的字符串复制回其中;

// nb: the function prototype has been slightly modified 
char** parse(char* userTyped, int *nargs){

    const char whitespace[2] = " "; //the deliminator
    char *strings;
    char **arr;
    int n = 0; // initially no element allocated

    strings = strtok(userTyped, whitespace);

    while( strings != NULL )
    {
        if( n ){ // if there are already allocated elements?
            arr = realloc( arr, ( n + 1 ) * sizeof( char** ) );
        }else{
            arr = malloc( ( n + 1 ) * sizeof( char* ) );
        }

        if( !arr ){
            perror( "parse" );
            exit( -1 );
        }

        // duplicate strings
        arr[ n ] = malloc( strlen( strings )+1 ); 

        if( !arr[ n ] ){
            perror( "parse" );
            exit( -2 );
        }
        strcpy(arr[ n ] , strings); // make a copy of the string

        n++;

        strings = strtok(NULL, whitespace);

    }


    // call freeStrArr when done with arr;
    //
    *nargs  = n; // save array size;
    return arr; // return string array
}

// this how to free the returned array;
void freeStrArr(char ** strarr,int n){
    while( n ){
        n--;
        free( strarr[ n ] );
    }
    free( strarr);
}

关于C 将字符串拆分为单个单词并将单个单词保存在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35142683/

相关文章:

c - C 中的二维数组和指针 - 如何访问元素?

c++ - 图遍历问题

c - 在struct中初始化函数指针

c - 创建链表时不需要创建实际节点吗?

c++ - 建立SSL连接并发送GET信息

c - 为什么 GCC 的 -Wconversion 对于 char 与 unsigned char 的行为不同?

c - 使用 bash 从 C 执行一组命令而不将它们存储在文件中

c - 将指针传递给不符合形式参数要求的函数

c - 使用管道,从父进程读取 2 个数字,子进程计算它们的总和并将结果提供给父进程进行打印

c++ - 以 "simple"形式获取 RSA key