Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assignment discards ‘const’ qualifier from pointer target type

Tags:

c

I'm trying to write a function which takes an extension from a string. When I try to compile the code below, I get this error:

excercises/12.c:8:20: warning: assignment discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers].

I would be really grateful if anyone helps me.

int get_extension (const char *file_name, char *extension) {
    for ( ; *file_name != '.'; file_name++);
    file_name++;
    for (extension = file_name; *file_name != '\0'; file_name++, extension++) 
        *extension = *file_name;
    puts (extension);
}

I tried to eliminate the const, and it works, but I wanna know why it doesn't work when the const is present. Thanks in advance

like image 967
Isma Jr Avatar asked Dec 29 '25 06:12

Isma Jr


1 Answers

You've assigned the pointer extension to have the same value as file_name, and then you dereference extension and write to it.

A const char * may be a string literal, but writing to a string literal invokes undefined behavior. Your code can do that, which is what the compiler is warning you about.

like image 59
Chris Avatar answered Dec 30 '25 21:12

Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!