简体   繁体   中英

Void pointers and dynamic memory allocation

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.

const is a type qualifier. In the C and maybe in many other programming languages, const applied to a data type indicates that the data is read only.

Passing 'const char *' to parameter of type 'void *' discards qualifiers

The above error you are getting because you are passing const object to a parameter that is not const ( (void *) in realloc ), and warning you about there is a possibility of changing (discards) the values pointed by const char* string by using void* ptr , that defeats the whole purpose of declaring the data as const .

But looking at the example, you are trying to allocate a memory for char* string , and after allocation, you would want to write something into that memory, if you make it const , how do expect it to write.

So you don't need your char* string to be const and hence, there is no need of cast to char* in realloc .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM