打印从C函数以字符*形式返回的字符串
我正在用C编写一个简单的shell程序。作为该程序的一部分,我正在编写一个标记器,将用户输入分解为标记。每次调用标记器时,它都返回下一个标记。标记器的代码如下所示:打印从C函数以字符*形式返回的字符串,c,shell,C,Shell,我正在用C编写一个简单的shell程序。作为该程序的一部分,我正在编写一个标记器,将用户输入分解为标记。每次调用标记器时,它都返回下一个标记。标记器的代码如下所示: char* nextToken(char string[]) { char token[50]= {}; //stores the current token //More code here, will post if necessary puts(token); return token; } int main() { cha
char* nextToken(char string[])
{
char token[50]= {}; //stores the current token
//More code here, will post if necessary
puts(token);
return token;
}
int main()
{
char inputString[] = "cpgm one two <three| script a b >file";
char *token = nextToken(inputString);
while(*token!='\0') //I'm using a char[] with a single null character as a delimiter to indicate the last token has been reached
{
token = nextToken(inputString);
}
}
while(*token!='\0')
{
puts(token);
token = nextToken(inputString);
}
试着从我的主函数中打印令牌,我看到的只是一个奇怪字符的列表,如下所示:
char* nextToken(char string[])
{
char token[50]= {}; //stores the current token
//More code here, will post if necessary
puts(token);
return token;
}
int main()
{
char inputString[] = "cpgm one two <three| script a b >file";
char *token = nextToken(inputString);
while(*token!='\0') //I'm using a char[] with a single null character as a delimiter to indicate the last token has been reached
{
token = nextToken(inputString);
}
}
while(*token!='\0')
{
puts(token);
token = nextToken(inputString);
}
�bHd?
�波黑
�波黑
�
�bHd
�
�bHd
�
�
�
�
�bHd
知道为什么会这样吗
谢谢。您正在堆栈上分配字符串
令牌。这意味着当您返回它时,它将被释放,并且不能再使用。您应该为字符串分配内存:
char *token = malloc(50);
然后,您还必须记住,在处理完字符串之后,通过调用
free(token);
您正在堆栈上分配字符串标记。这意味着当您返回它时,它将被释放,并且不能再使用。您应该为字符串分配内存:
char *token = malloc(50);
然后,您还必须记住,在处理完字符串之后,通过调用
free(token);
这是因为您正在访问垃圾值。nextToken()结束后,自动释放的令牌将被释放,成为调用者的垃圾值。要解决这个问题,可以将变量的生存时间更改为静态或进行动态内存分配。但正如你所知,它的大小,它可能不喜欢。只要做:
static char token[50];
这是因为您正在访问垃圾值。nextToken()结束后,自动释放的令牌将被释放,成为调用者的垃圾值。要解决这个问题,可以将变量的生存时间更改为静态或进行动态内存分配。但正如你所知,它的大小,它可能不喜欢。只要做:
static char token[50];
哇,谢谢!成功了!我想了好几个小时了!哇,谢谢!成功了!我想了好几个小时了!