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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With