char*返回值的函数有问题
我的职责是
char * GetUnreadMessageIndexes(char * input)
{
char index [10];
int i=0;
while(*input != ':')
{
input++;
}
input++;
while(*input != ',')
{
if(*input != ' ')
{
index[i]= *input;
i++;
}
input++;
}
return index;
};
我的测试代码主要是
char * b = "+CMGL:26867689, \"REC READ\",\"+81923733737\", \n test again ";
char * a = GetUnreadMessageIndexes(b);
while(a != ((int)a + (int) strlen(a)))
{
printf("%c",*a);
a++;
}
此函数假设解析+CMGL之后和之前的数字字符串,
我只得到第一个数字“2”,其他值是意外值,不正确
最佳答案
数组index
是函数GetUnreadMessageIndexes
的局部变量,一旦执行结束,index
就不再存在。使用指针并使用char
为10malloc
分配内存。
替换:
char index[0];
使用:
char *index = malloc(10);
此外,还需要空终止数组,否则
strlen
将无法正常使用它:while(*input != ',')
{
if(*input != ' ')
{
index[i]= *input;
i++;
}
input++;
}
index[i] = '\0';
因为现在数组是以空结尾的,而不是使用
while
循环来打印结果数组,只需使用:printf("%s", a);
现在你的代码按预期工作:Live Demo
关于c - char *返回值的功能,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21295951/