I need to encapsulate a literal string in a struct. The code below won't compile, but hopefully illustrates what I would like to do?
struct my_struct
{
char* str = "string literal";
};
You have to initialize the struct when you create an instance of the struct. struct my_struct { char* str; }; int main(int argc,char *argv[]) { struct my_struct foo = {"string literal"}; ... }
It's perfectly valid to return a pointer to a string literal from a function, as a string literal exists throughout the entire execution of the program, just as a static or a global variable would.
String literals are stored in C as an array of chars, terminted by a null byte. A null byte is a char having a value of exactly zero, noted as '\0'. Do not confuse the null byte, '\0', with the character '0', the integer 0, the double 0.0, or the pointer NULL.
The characters of a literal string are stored in order at contiguous memory locations. An escape sequence (such as \\ or \") within a string literal counts as a single character. A null character (represented by the \0 escape sequence) is automatically appended to, and marks the end of, each string literal.
You can't initialize any members in a struct declaration. You have to initialize the struct when you create an instance of the struct.
struct my_struct
{
char* str;
};
int main(int argc,char *argv[])
{
struct my_struct foo = {"string literal"};
...
}
Since you want the str
member to refer to a string literal, you'd better make it a const char *str
, as you can't modify string literals any way.
to initialize your struct to a known state every time.
struct my_struct
{
const char* str;
int bar;
};
void init_my_struct(strut my_struct *s)
{
s->str = "string literal";
s->bar = 0;
}
int main(int argc,char *argv[])
{
struct my_struct foo;
init_my_struct(&foo);
struct my_struct
{
const char* str;
int bar;
};
#define MY_STRUCT_INITIALIZER {"string literal",0}
int main(int argc,char *argv[])
{
struct my_struct foo = MY_STRUCT_INITALIZER;
struct my_struct
{
const char* str;
int bar;
};
const struct my_struct my_struct_init = {"string_literal",0};
int main(int argc,char *argv[])
{
struct my_struct foo = my_struct_init;
You'll have to create an instance of the struct, and then set the str
member. And if you plan to use string literals with it, you really should change it to const char* str
.
struct my_struct
{
const char* str;
};
int main() {
struct my_struct s1;
s1.str = "string literal";
/* or */
struct my_struct s2 = {"string literal"};
}
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