I'm trying to make a word counter program that takes a sentence and counts the number of words. I would like to use dynamic memory allocation because it has many advantages such as not having to worry about not enough space or too much empty space. Here is my code so far:
#include <stdio.h>
#include <stdlib.h>
const char *strmalloc(const char *string);
char *user_input = NULL;
int main(void) {
printf("Enter a sentence to find out the number of words: ");
strmalloc(user_input);
return 0;
}
const char *strmalloc(const char *string) {
char *tmp = NULL;
size_t size = 0, index = 0;
int ch;
while ((ch = getchar()) != '\n' && ch != EOF) {
if (size <= index) {
size += 1;
tmp = realloc((char*)string, size);
}
}
}
As you might know, the prototype for the realloc function goes like this:
void *realloc(void *ptr, size_t size)
When I use the realloc function in the while loop in the strmalloc() function, I get a warning saying:
Passing 'const char *' to parameter of type 'void *' discards qualifiers
I have no idea what this means but I know that I can get rid of it with a typecast to char*
However, I've learned that I shouldn't use a typecast just to prevent a warning. I should learn what the warning is warning me about and decide whether a typecast is the right thing. But then again, I know that a pointer to void accepts any data type, and to specify one, a typecast is required. So my question is, should I keep the typecast in the realloc() function or get rid of it and do something else.