ここで私は独自のrealloc関数を書こうとしています。古い配列を新しい配列にコピーしてしまいました。 1つのファイルに16文字以下の文字列しか含まれていない場合でも問題ありません。問題は、元のセットアップ16以上の行に発生します。つまり、私の考えるrealloc関数の実装に問題があることを意味します。私のプログラムでは、配列の変更を制御する3つのステップを設定しました。私自身のrealloc関数の実装を
私の考えは次のとおりです。
まずステップ:ファイルの行未満または16に等しい、
第二ステップnew_arrayする値与える:17に等しいファイルの行を、1以上をmalloc必要がありますスペース。古い配列を新しい配列にコピーして、最後のスペースに現在の行を与える
第3ステップ:第2ステップと同様ですが、古い配列は前の拡張配列です。
今のところ、私はそれがうまくいかない理由を理解するのに苦労しています。そして、私のファイルは、例えば、正確に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.
あるutitlityFunction.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'引数はバイト数ですが、要素数を渡します –
@ M.M utitlityFunction.cの 'malloc'を意味しますか?私は試しました...しかし、結果は変わっていません...最初の2つの数字と最後の数字だけが表示されていたのは混乱します... – HxH
配列のインデックスとして 'i'の代わりに' countLine'を使うべきではありません? – alk