我試圖將c文件的每一行添加到數組中。 files.txt的內容是從c文件讀取行並將字符串放入數組
first.c
second.c
third.c
fourth.c
我想我的代碼打印每行的內容,行添加到我的數組,然後打印出我的陣列中的每個條目。現在它正確地完成了第一部分,但它只是將第四個c添加到數組中。有人能告訴我我的代碼有什麼問題嗎?
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int i=0;
int numProgs=0;
char* programs[50];
char line[50];
FILE *file;
file = fopen("files.txt", "r");
while(fgets(line, sizeof line, file)!=NULL) {
//check to be sure reading correctly
printf("%s", line);
//add each filename into array of programs
programs[i]=line;
i++;
//count number of programs in file
numProgs++;
}
//check to be sure going into array correctly
for (int j=0 ; j<numProgs+1; j++) {
printf("\n%s", programs[j]);
}
fclose(file);
return 0;
}
沒有ü意味着'的sizeof(線)'? – CinCout 2014-10-22 07:26:37
@gargankit'sizeof line'也是正確的。 – 2014-10-22 07:32:09
這一行:programs [i] = line;將不會有兩個原因。 1)對於char指針的50個指針的數組需要爲這50個指針中的每一個指針分配內存(並設置指向該內存的指針)。建議您使用calloc(),這樣內存段將被預先設置爲全部'\ 0'。 2)所有這一行正在做的是將程序[i]指針設置爲指向數組行[]。真正需要的是類似於:strcpy(programs [i],line); – user3629249 2014-10-22 09:01:47