1

I'm trying to learn C, and would like to have a function that takes a filename, reads each line of the file into an array and returns that array (or a pointer to it, but I guess that in the case of arrays, it's almost always a pointer already) to main(). But I'm having the warning below, so there must be something not right in the code:

warning: incompatible pointer to integer conversion assigning to 'char' from
      'char [1024]' [-Wint-conversion]
                a_line[n - 1] = line;
                              ^ ~~~~
1 warning generated.

The code is:

#define BUFFER_MAX_LENGTH 1024
#define EXIT_FAILURE 1

char * read_lines_to_arr(char *fname, FILE **fp) {

    char line[BUFFER_MAX_LENGTH];
    // initialise array to store lines
    // https://stackoverflow.com/questions/11198604/
    // static, because otherwise array would be destroyed when function finishes
    static char * a_line  = NULL;
    int n = 0;

    *fp = fopen(fname, "r");

    // Check for error....
    if (*fp == NULL){
        printf("error: could not open file: %s\n", fname);
        exit(EXIT_FAILURE);
    }

    while (fgets(line, sizeof(line), *fp) != NULL) {
        /*
        fgets doesn't strip the terminating "\n" so we do it manually
        */
        size_t len = strlen(line);
        if (line[len - 1] == '\n') {  // FAILS when len == 0
            line[len -1] = '\0';
        }
        // printf("%s", line);

        a_line = realloc (a_line, sizeof (char*) * ++n);
        if (a_line == NULL)
            exit (-1);  // memory allocation failed

        a_line[n - 1] = line;  // <- this line is giving the warning
    }

    a_line = realloc(a_line, sizeof (char*) * (n + 1));
    a_line[n] = 0;

    return a_line;
}

I think I need to use realloc/malloc in this case because I don't know how many lines the file will have.

Any help to solve/understand this would be kindly appreciated.

Biffen
  • 6,249
  • 6
  • 28
  • 36
PedroA
  • 1,803
  • 4
  • 27
  • 50
  • 1
    You cannot assign *strings*. You need `strcpy()`; – pmg Jun 03 '19 at 11:45
  • 1
    Use `strcpy`, this is covered in the chapter dealing with strings in your beginner's C book. `a_line[n - 1] = line` -> `strcpy(a_line[n - 1], line)`. Also `realloc (a_line, sizeof (char*) * ++n);` -> `realloc (a_line, sizeof (char) * ++n);`, you want n times the size of char, not n time s the size of a _pointer_ to char. There may be more problems though, I didn't check everything. – Jabberwocky Jun 03 '19 at 11:51
  • 1
    Also `static char * a_line = NULL;` -> `char * a_line = NULL;`. Former is not wrong, but totally unnecessary. Find out why as an exercise. – Jabberwocky Jun 03 '19 at 11:56
  • doing `strcpy(&a_line[n - 1], line);` solved the issue. I'm reading K&R C prog. language but haven't started where `strcpy ` is used in "Pointer Arrays; Pointers to Pointers". Found it now. – PedroA Jun 03 '19 at 11:56

0 Answers0