Use and complete the template provided. The entire template must be completed. If you don't, your post may be deleted!
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.
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?
}