I have the following struct,
struct example_struct {
int number ;
char word[100]
}
Which I initialize in my code as a constant struct
const struct example_struct example {
.number = 5
} ;
strcpy(example.word, "some_string") ;
which gives me the warning when I try to compile my code:
"warning: passing argument 1 of ‘strcpy’ discards ‘const’ qualifier from pointer target type"
I realize that I shouldn't be trying to assign a value of a struct when I make it a const struct, but I can't put the stringcpy inside the struct either. Is there any way I can assign a string to an element of a const struct in c?
The warning is correct - since you declared your struct withconst` qualifier, copying data into it at runtime is undefined behavior.
You could either drop the qualifier, or initialize your struct like this:
const struct example_struct example = {
.number = 5
, .word = "some_string"
};
This would put a null-terminated sequence of characters from "some_string" into the initial portion of the word[100] array, and fill the rest of it with '\0' characters.
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