3
votes

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?

1
You could create a non-const instance and use that as the initializer for the const, if you happen to be using non literal strings. Just remember to initialize/assign the entire array before that. - Ilja Everilä
@IljaEverilä Are you saying I could create a non-const instance of the string or the struct? - physics_researcher
Of the struct, copy over the string, and use the non const struct as the initializer of the const struct. But it's rather pointless, if you're initializing from a string literal, as shown in the answer you've accepted. - Ilja Everilä

1 Answers

6
votes

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.