具体来说,我有一个字符串,说“ Hello world”。我想用“”将它分开(即将其拆分为单词),并借助char * temp指针将这些单词存储到数组中,但是由于我可能会读取不同长度的字符串,最初我不知道输入字符串中存在的单词数,因此要实现这一点,我最初为“ * temp”指针分配了一块内存(假设我可以存储地址第一个令牌(即第一个单词)),然后如果我遇到字符串中的第二个单词,我将重新分配2个内存块,以便'temp [0]'可以扩展为'temp [1]'并可以指向到给定字符串中的第二个单词。 .....类似地,当字符串中出现第n个单词时,'* temp'指针通过'realloc()'函数扩展为n个块。 但是当我编译我的代码时,它给出了一条错误消息“ Segmentation fault(core dumped)”。 我在哪里错了?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char name[20] = {"Hello world"};
char *p = strtok(name, " ");
//char *temp[4]; //If I initialize temp as array of pointer this is working well
char *temp;
temp = (char*)malloc(sizeof(char));
int n = 1;
while(p!= NULL)
{
temp = (char*)realloc(temp,(n)*sizeof(char));
temp[--n] = p;
p = strtok(NULL," ");
++n;
}
for (int i = 0; i < 2; ++i)
printf("%s\n", temp[i]);
return 0;
}