【发布时间】:2014-03-14 22:47:38
【问题描述】:
我在我的程序中尝试做的是将一个字符串的内容反向复制到另一个字符串。这部分程序有效。
但是,我不想限制用户的输入,所以我想使用 malloc 和 realloc。这是我的代码:
#include <stdio.h>
#include <stdlib.h>
/*copy one string to another, in reverse*/
void copyStr(char *p, char *h){
int i=0,j=0;
int length=0;
length=strlen(p); int l=length;
for (i=0; i<length; i++){
h[i]=p[l-1];
l--;
}
char *temp=&h[0];
for (i=0; i<length; i++){
printf("%c",temp[i]);
}
}
main(){
printf("please enter a string\n");
char c; int i=0; int end=10;
/*allocate initial memory*/
char *p=(char*)malloc(sizeof(end)); char *temp=p;
while (c!='\n')
{
/*reallocate if needed*/
if (i==(end-1)){
end*=2;
temp = realloc(p,end*sizeof(temp));
if (temp!=NULL){
/*this is for myself, to see what the error was*/
printf("error allocating\n");
exit(1);
}
else
free(p);
}
c=getchar();
p[i]=c;
i++;
}
char h [sizeof(p)];
copyStr(p,h);
}
我发现 realloc 函数不起作用,所以我请求您的帮助。
如果输入很短(即 3 个字符),程序就可以工作。 如果超过 10 个字母,则不会重新分配内存。 如果它长于 5,它将反向打印,但会向我发送一条名为“堆栈粉碎”的消息。 谢谢。
【问题讨论】:
-
也许
temp=(char*)realloc(p,end*sizeof(temp));会起作用...因为*temp=(char*)realloc(p,end*sizeof(temp));看起来很奇怪。 -
temp = realloc(p, end * sizeof *temp); -
两个都试过了,还是不行……
标签: c string stack malloc realloc