Malloc - unlimited input from user

Use and complete the template provided. The entire template must be completed. If you don't, your post may be deleted!

  1. The problem statement, all variables and given/known data:

I'm trying to get an unlimited input of words with an unlimited number characters from the user using
malloc and pointer to pointer then printing the inputs if only the user inputted the word "end". Even if the user
presses enter, the program should still ask input until there is no "end" inputted.
Can you please help me, I don't know if I'm doing right.

  1. Relevant commands, code, scripts, algorithms:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main () {

    char** pointer = malloc(sizeof(char**) * 5000);
    fgets(pointer, 5000, stdin);
    if (strncmp(pointer, "end", 5000) == 0) {
        puts(pointer);
        puts("\n");
    }
    return 0;
}
  1. The attempts at a solution (include all code and scripts):

  2. Complete Name of School (University), City (State), Country, Name of Professor, and Course Number (Link to Course):

AcSat QC Philippines, Mr. Jules Morcilla , CS13

Note: Without school/professor/course information, you will be banned if you post here! You must complete the entire template (not just parts of it).

You can look what one of your classmates got for replies here:

You're using too many *'s. Wherever you see * in front, imagine an [] at the end: ** would be an array of arrays.

sizeof(char **) doesn't make sense either. You want 5000 characters. How large is one character? sizeof(char). How large is 5000 of them? sizeof(char) * 5000.

char *buffer=(char *)malloc(sizeof(char)*5000);

Next, you don't need strncmp, strcmp() will do. fgets() and the like NULL-terminate their strings properly.

Last, how do you handle unlimited input? you can use realloc() to extend the size of an existing block of memory.

buffer=realloc(buffer, 10000*sizeof(char));

You can even call realloc() on a NULL pointer(pointer to nothing) -- it will know to just give you fresh data. So you can just run the exact same code every loop, the first time isn't anything special.

So:

int main(void)
{
        int pos=0; // pos:  how many bytes have been read already
        int size=0; // size:  how large the buffer is
        char *buffer=NULL; // The data buffer

        buffer=realloc(buffer, pos+5000); // Add 5000 more bytes.
        if(buffer == NULL)
        {
                printf("out of memory\n");
                return(1);
        }
        size=pos+5000; // We need 5000 bytes past the end of the last data
        fgets(buffer+pos, 5000, stdin); // Read it 'pos' bytes past the start of the buffer, to add to the end
        pos=strlen(buffer); // How long is the data in the buffer now?
}

Thanks to all, this forum really helps.