Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign a string to constant struct

Tags:

c

string

struct

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?

like image 840
physics_researcher Avatar asked Jan 20 '26 04:01

physics_researcher


1 Answers

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.

like image 168
Sergey Kalinichenko Avatar answered Jan 21 '26 20:01

Sergey Kalinichenko