내 프로그램에서 수행하려는 작업은 한 문자열의 내용을 다른 문자열로 역순으로 복사하는 것입니다. 이 프로그램의 일부가 작동합니다.메모리를 다시 할당하면 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보다 길면 역순으로 인쇄되지만 "stack smashed"라는 메시지가 나에게 전송됩니다. 감사합니다.
어쩌면'온도 = (숯불 *) realloc을 (P, 최종 *의를 sizeof (온도가))'일 것이다 ...'때문에 * 온도 = (char *) realloc (p, end * sizeof (temp));'이상하게 보입니다. – francis
'temp = realloc (p, end * sizeof * temp); – wildplasser
모두 시도했지만 여전히 작동하지 않습니다 ... – Alan