여기 내 자신의 realloc 함수를 작성하려고하는데 이전 배열을 새 배열에 복사하려고했습니다. 하나의 파일에 각 줄의 문자열 수가 16 개 이하인 경우에는 문제가되지 않습니다. 문제는 원래 설정 16 이상의 줄이 발생할 때. 문제는 내 realloc 함수 구현을 의미합니다. 내 프로그램에서는 배열의 변경을 제어하는 세 단계를 설정했습니다.내 자신의 realloc 함수 구현에 C
내 생각이다
첫번째 단계는 파일의 라인은 16보다 작거나 같음, new_array하는 값을 제공하는 경우
번째 단계 : 17과 동일한 파일의 라인, MALLOC해야 하나 이상의 공간. 이전 배열을 새로운 배열에 복사하고 마지막 줄에 현재 줄을 지정하십시오.
세 번째 단계 : 두 번째 단계와 비슷하지만 이전 배열은 이전 확장 배열입니다.
지금은 왜 작동하지 않는지 알아 내려고 애 쓰고 있습니다. 내 파일이 예를 들어 정확히 17 라인,이 때 :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
을 결과는
#include "utilityFunction.h"
#include <stdlib.h>
#include <string.h>
#include <stdlib.h>
char **extendArray(char **oldArray, int oldLen, int newLen){
char **newptr = malloc(newLen * sizeof (char*)); //updated here. No changed for result
// if(newptr == NULL){
// perror("Failed to allocate");
// exit(1);
// }
memcpy(newptr, oldArray, oldLen);
free(oldArray);
return newptr;
}
내 주요 기능 코드 utitlityFunction.c
here start
1
2
(null)
(null)
(null)
(null)
(null)
(null)
(null)
(null)
(null)
(null)
(null)
(null)
(null)
(null)
17
The file 'foo' had 17 lines.
입니다 다음과 같이
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "utilityFunction.h"
int main(int argc, char**argv){
FILE *filename;
size_t len = 0;
char *line = NULL;
int index;
int countLine = 0, i = 0;
char** new_array = malloc(16 * sizeof(char*));
char** extended_array;
char* current_line;
for(index = 1; index < argc; index++){ //loop for all files name you input in the command line
filename = fopen(argv[index], "r");
if(filename == NULL){
printf("The file '%s' did not exist.\n", argv[index]);
}else{
while(getline(&line, &len, filename)!=EOF){
current_line = strdup(line);
if(new_array == NULL){
perror("Failed to allocate");
exit(1);
}
if(i<16){
new_array[i] = current_line;
}
else{
if(i==16){ //actually index 17
extended_array = extendArray(new_array, i, countLine);
extended_array[i] = current_line;
}else{
printf("aaa?\n");
extended_array = extendArray(extended_array, i, countLine);
extended_array[i] = current_line;
}
}
i++;
countLine++;
}
//mprintf("%s\n", extended_array[0]);
//mprintf("-->m%d\n", countLine);
printf("here start\n");
int j;
for(j = 0; j < countLine; j++){
printf("%s\n", extended_array[j]);
}
//print line result after end of file
printf("The file '%s' had %d lines.\n", argv[index], countLine);
}
}
}
이 난 그냥 손실입니다 ....
충분한 메모리를 할당하지 않았습니다. 'malloc' 인수는 바이트 수이지만 요소 수를 전달합니다 –
@ M.M utitlityFunction.c에서 'malloc'을 의미합니까? 나는 시도했다. 그러나 결과는 바뀌지 않았다 ... 그래서 처음 두 숫자와 마지막 숫자 만 출력했는지 혼란 스럽다. ... – HxH
배열의 인덱스로'i' 대신에'countLine'을 써서는 안된다. ? – alk