1
"done"이라는 단어가 소개 될 때까지 일부 단어를 읽길 원합니다. 이 단어들은 동적으로 할당 된 행렬에 저장되며, 수신 된 각 입력에서 수정됩니다. 문제는 3 단어가 지나면 프로그램이 충돌하고 경고로 넣은 "메모리 할당 실패"메시지가 나타납니다. 내 재 할당에 문제가 있습니까?배열의 재 할당이 실패했습니다.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_DIM 100
int main()
{
char **words,buff[100];
int i,dim = 0;
words = (char**)calloc(dim,dim*sizeof(char*));
while(strcmp(buff,"done"))
{
printf("the new word : ");
scanf("%100s", buff);
if(strcmp(buff,"done"))
{
dim++;
words = (char**)realloc(words,dim*sizeof(char*));
if(words == NULL)
{
printf("Memory allocation failed !\n");
exit(0);
}
words[dim] = (char*)calloc(MAX_DIM,sizeof(char));
strcpy(words[dim],buff);
}
}
printf("%d", dim);
for (i = 0;i < dim;i++)
free(words[i]);
free(words);
return 0;
}
없음 없음 없음에
에서 코드의 마지막 부분을 수정하여 해결할 수 있습니다! 인덱스는 0에서 n-1까지이므로 'words [dim]'는 범위를 벗어납니다! –
이'scanf ("% 100s", buff);은'scanf ("% 99s", buff);'이어야합니다. C "문자열"은'0' 터미네이터를 저장하기 위해 더 많은'char'를 필요로합니다. 또는 이것을 뒤집기 위해서 : C "strings"은'0' 터미네이터를 저장하기 위해'char'가 필요하기 때문에 할당되지 않은 하나의'char'를 제공합니다. – alk
또한'sizeof (char)'는 정의에 의해'1'과 동일합니다. – alk