【发布时间】:2014-11-17 22:24:25
【问题描述】:
我正在尝试使用指针修剪字符串(从字符串的开头和结尾删除空格)。
char* killspace(char *a)
{
char *enda = NULL;
int i = 0, spaceS = 0, spaceE = 0, bigend = 0 , out = 0, taille = strlen(a);
do
{
if (a[i] == ' ')
{
spaceS++;
}
else
{
out = 1;
}
i++;
} while (out == 0);
out = 0;
do
{
if (a[taille] == ' ')
{
spaceE++;
}
else
{
out = 1;
}
taille--;
} while (out == 0);
bigend = (spaceE + spaceS);
// new size
enda = (char *)calloc((strlen(a)-bigend), sizeof(char));
i = 0;
for (int j = spaceS; j < (strlen(a)-spaceE); j++)
{
enda[i] = a[j];
i++;
}
return(enda);
free(enda);
}
bigend 是字符串开头和结尾的空格数。
但返回的结果有一些随机字符,如“ýýýý««««««««îþîþîþ”
【问题讨论】:
-
您忘记在字符指针末尾添加“\0”来以空值结尾。
-
无条件
return之后的free()应该达到什么目的? -
我把free释放内存,没有条件返回
-
free永远不会被执行。你的编译器会警告你。您确实启用了警告,然后正确地阅读了它们?
标签: c pointers dynamic-memory-allocation