Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 将包含多个单词的字符串转换为字符数组_C_Arrays_String_Char - Fatal编程技术网

C 将包含多个单词的字符串转换为字符数组

C 将包含多个单词的字符串转换为字符数组,c,arrays,string,char,C,Arrays,String,Char,假设我有以下字符串: char input[] = "this is an example"; 我想把这个字符串作为数组中的一个条目, 如何将其放入这样的数组中: char inputArray[] = {"this","is","an","example"}; 您可能不知道自己想要什么,或者您想要以下内容: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ct

假设我有以下字符串:

char input[] = "this is an example";
我想把这个字符串作为数组中的一个条目, 如何将其放入这样的数组中:

char inputArray[] = {"this","is","an","example"};

您可能不知道自己想要什么,或者您想要以下内容:

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

int main(void) 
{
    char input[] = "this is an example";

    size_t n = 0;

    for ( char *p = input; *p;  )
    {
        while ( isspace( ( unsigned char )*p ) ) ++p;

        if ( *p )
        {
            ++n;
            while ( *p && !isspace( ( unsigned char )*p ) ) ++p;
        }
    }

    char * inputArray[n];

    size_t i = 0;
    for ( char *p = strtok( input, " \t" ); p != NULL; p = strtok( NULL, " \t" ) ) inputArray[i++] = p;

    for ( i = 0; i < n; i++ ) puts( inputArray[i] );

    return 0;
}

您不能这样做,因为char inputArray[]的每个元素都是char类型,并且它不能存储字符串或字符串指针。请在下次之前展示您的研究成果。请先阅读第页。我投票结束这个问题,因为这显然是一个写我的代码的请求,而不是一个问题。请先看第一页谢谢你的反馈,我一直在努力提高自己!这就是我想要的,我只是有一个很难措辞的问题:-@peterLeg考虑到原始数组是由strtok函数更改的。它在字符串中插入了零个字符以将其拆分为单词..也许与其遍历输入字符串两次,不如根据需要在带有strtok调用的循环中为inputArray分配空间。@pmg当内存将在循环中每次重新分配时。我对VLA有一点看法。当客户端尝试2M长的字符串时,它们往往在最糟糕的时候失败。需要更多的管理来保留两个元素,以便根据需要扩展阵列,从而提高安全性。
this
is
an
example