我在我的程序中試圖做的是將一個字符串的內容以相反的方式複製到另一個字符串中。該計劃的這部分工作。重新分配內存不能在c中工作
但是,我不想限制用戶輸入,所以我想使用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,它將反向打印,但會發送一條消息,稱爲「堆棧被搗毀」。 謝謝。
也許'溫度=(字符*)的realloc(P,端的sizeof *(溫度));'將工作...因爲'*溫度= (char *)realloc(p,end * sizeof(temp));'看起來很奇怪。 – francis
'temp = realloc(p,end * sizeof * temp);' – wildplasser
兩者都試過,仍然不起作用... – Alan