0

I will show only the important part of the problem so it's gonna be easy to understand my doubt. Suppose I am opening a file where each line is a string with a student's name.

Why does it work:

    FILE * studentFile;
    studentFile = openFile("students.txt", "r");

    char ** students;
    students = (char**)malloc(100 * sizeof(char*));

    if (students == NULL) {
        exit(2);
    }

    int np;
    int a = 0;

    while (!feof(studentFile)) {

        students[a] = (char *)malloc(sizeof(char));

        if (students[a] == NULL) {
            exit(3);
        }

        np = fscanf(studentFile, "%s", students[a]);

        if (np != EOF) {

            ++a;

        }
    }

And it doesn't? :

        FILE * studentFile;
        studentFile = openFile("students.txt", "r");

        char * students;
        students = (char*)malloc(100 * sizeof(char));

        if (students == NULL) {
            exit(2);
        }

        int np;
        int a = 0;

        while (!feof(studentFile)) {

            np = fscanf(studentFile, "%s", students[a]);

            if (np != EOF) {

                ++a;

            }
        }
Joe
  • 109
  • 6
  • 1
    `char *` is simply not the same as `char **`. On one hand, you have a string (null-terminated `char *`) and on the other hand you have a pointer to an array of 10 of these `char *`s, one per student. You could think of it like `char *` = one student, `char **` = many students. Also, see [do I cast malloc?](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – ggorlen May 21 '20 at 01:30
  • 1
    A few links that provide basic discussions of pointers may help. [Difference between char *pp and (char*) p?](https://stackoverflow.com/a/60519053/3422102) and [Pointer to pointer of structs indexing out of bounds(?)...](https://stackoverflow.com/a/60639540/3422102) Basic difference, `char *` is a *pointer-to-char* while `char**` is a *pointer-to-pointer-to-char*. There is one-level of *indirection* difference between them. If you allocate for `char*` you allocate characters. If you allocate for `char**` you allocate pointers. – David C. Rankin May 21 '20 at 01:38
  • 1
    Also, in C, there is no need to cast the return of `malloc`, it is unnecessary. See: [Do I cast the result of malloc?](http://stackoverflow.com/q/605845/995714) – David C. Rankin May 21 '20 at 01:41
  • 2
    `students[a] = (char *)malloc(sizeof(char));` That allocates a 1-char sized buffer, which the next `fscanf` will promptly overflow. So, no, the first version of the code does not work either. – dxiv May 21 '20 at 02:03

0 Answers0