打印動態分配的數組時出現分段錯誤。我不熟悉動態分配的數組,所以這可能是一個問題。如果我註釋掉打印數組中每個元素的for循環,我的程序就會編譯好。所以我覺得我的readText函數很好,但我可能是錯的。在問這個問題之前,我已經做了研究,但我找不到答案。我只需要能夠打印出text1數組的每個元素。這裏是我的代碼:在c中打印數組時出現分段錯誤
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int ch1, ch2;
int size1, size2;
FILE *fh1, *fh2;
if(argc<3) {
printf("need two file names\n"); return(1);
}
if(!(fh1 = fopen(argv[1], "r"))) {
printf("cannot open %s\n",argv[1]); return(2);
}
if(!(fh2 = fopen(argv[2], "r"))) {
printf("cannot open %s\n",argv[2]); return(3);
}
if(argc>3) {
if(!(fh3 = fopen(argv[3], "w+"))) {
printf("cannot open %s\n",argv[3]); return(4);
}
}
fseek(fh1, 0, SEEK_END);
size1 = ftell(fh1);//Getting fh1 size
fseek(fh1, 0, SEEK_SET);
fseek(fh2, 0, SEEK_END);
size2 = ftell(fh2);//Getting fh2 size
fseek(fh2, 0, SEEK_SET);
char* readText(int, FILE*);//declaring function
char *text1 = readText(size1, fh1);
int i;
for (i=0; i<size1; i++)
printf("text1[%d] = %s\n", i, text1[i]);
return 0;
}
char *readText(int size, FILE *fh)//reads file into a dynamically allocated array
{
char * text = malloc(size * sizeof(char));
int i=0;
while(!(feof(fh)))
{
fgets(text, size, fh);
++i;
}
return text;
}
抱歉,Stack Overflow是不是在這裏調試代碼爲您服務。在調試器下運行該程序,並從崩潰點開始逆向工作。 –
感謝您發佈您的代碼,但請在您的問題中多加一點說明:您有什麼問題,您期望得到什麼結果,以及[您嘗試過什麼](http://whathaveyoutried.com)到目前爲止?通過[問題清單](http://meta.stackexchange.com/questions/156810/stack-overflow-question-checklist)將幫助我們更好地回答你的問題。謝謝! –