假設我想「重用」一個char指針數組,像在下面的程序中循環參數列表中給出的文件,循環文件中的行,將它們添加到動態分配的數組中,然後打印它:重用char指針數組
// includes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
// globals
int progReturn = 0;
int globalLineCounter = 0;
////// main
int main(int argc, char *argv[]) {
FILE *fp;
int i;
// iterate files. first arg is the program name
for (i = 1; i < argc; i++) {
fp = fopen(argv[i], "r");
if (fp == NULL) {
fprintf(stderr, "The file '%s' did not exist.\n", argv[i]);
progReturn = 1;
} else {
// read lines from the file
char line[256];
// THE PROBLEM: I'd like to completely clear this array.
char **lines = malloc(16 * sizeof(char*));
// iterate lines
int fileLineCounter = 0;
while (fgets(line, sizeof(line), fp)) {
// remove newline
strtok(line, "\n");
// add lines to array
lines[globalLineCounter] = malloc(256 * sizeof(char));
strcpy(lines[globalLineCounter], line);
//printf("%s\n", lines[globalLineCounter]); // tester
fileLineCounter++;
globalLineCounter++;
}
// all lines read
printf("The file '%s' had %d lines.\n", argv[i], fileLineCounter);
// print the array
int j=0;
for (j=0; j<fileLineCounter; j++) {
// PROBLEM: Garbage from the second file when it prints here.
printf("%s\n", lines[j]);
}
// delete lines, delete file
memset(lines, 0, sizeof(*lines));
fclose(fp);
}
}
// all files read
return progReturn;
}
在第一個文件,一切正常,沒有問題。在第二個文件中,當我打印數組時,它顯示了不可打印的字符以及第一個文件中的一些行。
什麼可能導致此問題?我沒有完全清除**lines
?
編輯:例如輸入和輸出:
輸入文件foo:
This is a test
of the lineSort program
in order to
test its capabilities.
Lots of whitespace too!
aaa
bbb
cccccc
aaa
ggggg
hhhhh
fffff
eeeee
ddddd
ppppp
輸入文件欄:
aaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbb
zzzzzzzzzzzzzzzzz
ccccccccccccccccc
yyyyyyyyyyyyyyyyy
輸出sortLine foo bar
:
The file 'foo' had 20 lines.
cccccc
Lots of whitespace too!
This is a test
aaa
aaa
bbb
ddddd
eeeee
fffff
ggggg
hhhhh
in order to
of the lineSort program
ppppp
test its capabilities.
The file 'bar' had 5 lines.
(x▒▒
(x▒▒
Lots of whitespace too!
in order to
test its capabilities.
你不會在那裏重複使用任何東西。 – melpomene
無關挑剔:'的sizeof(char)的''是通過定義1',所以通過將其相乘是不必要的。 – Arkku
http://stackoverflow.com/help/mcve – melpomene