c - 将字符串拆分为字符串数组

标签 c arrays

我正在尝试创建一个函数,它将一个字符串作为参数,将它分成多个字符串,其中单词用空格分隔,将它保存到一个数组并通过指针返回它。尽管将内存静态分配给数组,但由于段错误,地址被占用,程序崩溃。这段代码有什么问题?

void separate_words(char* full_text, char *matrix[], int* how_many)
{
char tmp;
int actual_letter,which_letter=0;
for(actual_letter=0;actual_letter<strlen(full_text);actual_letter++)
{
    if(full_text[actual_letter]!=32)
{


    full_text[actual_letter];
    matrix[*how_many][whitch_letter]=full_text[actual_letter];//here crashes
}
else
{  
    *how_many++;
    which_letter=0;
}
}

//*how_many
}

/*...*/
char words[20][20];
char text[20];
int number_of_words=0;
separate_words(text,words,&number_of_words);

最佳答案

当您使用 strtok

时,这是一个典型的问题
#include <stdio.h>
#include <string.h>

void separate_words(char* full_text, char *matrix[], int* how_many)
{
    char *pch;
    pch = strtok (full_text," \t\n");
    int i = 0;
    while (pch != NULL)
    {
        matrix[i++] = pch;
        pch = strtok (NULL, " \t\n");
    }
    *how_many = i;
}

int main ()
{
    char str[] = "apple   banana orange pineapple";
    char *matrix[100] = { NULL };
    int how_many = 0;
    separate_words(str, matrix, &how_many);

    int i;
    for( i = 0; i < how_many; i++ )
    {
        if( matrix[i] != NULL )
        {
            printf( "matrix[%d] = %s\n", i, matrix[i] );
        }
    }
    return 0;
}

输出:

matrix[0] = apple
matrix[1] = banana
matrix[2] = orange
matrix[3] = pineapple

关于c - 将字符串拆分为字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33704362/

相关文章:

javascript - 在函数内对编号数组进行排序

c++ - 如何用逗号分隔从文件中读取的字符串,然后将其保存在数组中

c - 为什么这不指向数组中的空字符? ('\0')

c - 使用 fgetc 读取文件意外停止

c - 按顺序向 EEPROM 写入和读取数据

c - 在 Linux 上模拟电路和编程微 Controller

python - R `summary` python中最接近的等价函数

python - Numpy 广播数组

c - 如何在c中使用结构体数组调用下一个元素

c - 链接器错误 :/usr/bin/ld: cannot find -lc