-1

I get a segmentation fault when printing a dynamically allocated array. I'm not familiar with dynamically allocated arrays so this could be a problem. My program compiles fine if I comment out the for loop where I'm printing each element of the array. So I feel like my readText function is fine but I could be wrong. I've done research before asking this question and I can't find an answer. I just need to be able to print out each element of the text1 array. Here is my code:

#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;
}
4

2 回答 2

2

text1[i]不是字符串,而只是一个字符。%s需要一个指向字符串开头的指针,所以你想要

printf( "text[%d] = %c\n", i, text1[i] );
于 2013-10-30T22:59:33.983 回答
0

由于%s说明符需要一个类型的参数char*,这些行:

for (i=0; i<size1; i++)
    printf("text1[%d] = %s\n", i, text1[i]);

text1其视为字符串数组,即char* []char**分别。

然而text1只是一个char*,所以你可以用它%c来打印一个字符:

printf("text1[%d] = %c\n", i, text1[i]);
于 2013-10-30T22:59:54.283 回答