Здесь я пытаюсь написать свою собственную функцию realloc, и я застрял на копировании старого массива в новый массив. Это не проблема, если один файл содержит только 16 или даже меньше строк в каждой строке. Проблема возникает, когда строки поверх исходной настройки 16. Это означает, что проблема связана с моей реализацией функции realloc, я думаю. В моей программе я установил три шага для управления изменениями массива.
Моя мысль такова:
Первый шаг: когда строка файла меньше или равна 16, присвойте значение new_array
Второй шаг: когда строка в файле равна 17, надо выделить еще один пробел. скопируйте старый массив в новый и передайте текущую строку последнему пробелу
Третий шаг: аналогичен второму шагу, но старый массив является предыдущим расширенным массивом.
На данный момент я изо всех сил пытаюсь понять, почему это не работает. И когда в моем файле ровно 17 строк, например:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Результат
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.
utilityFunction.c
#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;
}
Мой основной код функции выглядит следующим образом.
#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
аргумент - это количество байтов, но вы передаете количество элементов - person M.M   schedule 06.11.2016countLine
вместоi
в качестве индекса массива? - person alk   schedule 06.11.2016sizeof (char*)
. Середина звезды:*
. Это массив указателей. - person alk   schedule 06.11.2016countLine
равно ‹=i
, поэтому при использованииi
для индексации массива новый массив может быть небольшим при перераспределении наcountLine
записей. - person alk   schedule 06.11.2016