gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:45:56 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com