我编写了一个程序,在main函数中我声明了一个指针数组,然后我调用一个函数,它拆分一个给定的句子然后想把它分配给指针数组main().我无能为力.您能否查看下面粘贴的代码:
int main(void)
{
char *data[3];
allocate(data);
/* Unable to print the strings here */
printf("Main is %s\n", data[0] );
printf(""
}
void allocate(char **dt)
{
int i;
char buf[] = "The great Scorpion";
char delims[] = " ";
size_t len;
char *p;
char *result = NULL;
result = strtok(buf," ");
*dt = result;
int j = 1;
while(result!=NULL)
{
result = strtok( NULL, delims );
dt[j]=result;
j++;
}
/* able to print values here */
printf( "result is %s\n", dt[0]);
printf( "result is %s\n", dt[1] );
printf( "result is %s\n", dt[2] );
}
Run Code Online (Sandbox Code Playgroud)
有人可以帮帮我吗?
Pav*_*aev 14
strtok不分配新的字符串,它返回一个指向现有的字符串(并替换空字符分隔符的地方).所以在allocate,你填写dt指针buf.由于buf是一个自动变量,它的生命周期在allocate返回时结束,并且所有指针dt都无效.