Reputation: 426
struct Test {
char *s;
};
Test test;
test.s = "Hey";
or
char *s;
s = "Hey";
So I don't need the string to be edited, or anything like that. I was just wondering if the code above me is allowed, or is safe to use?
And if this should not be used, why?
Or, if there is a better way I should do this?
Upvotes: 1
Views: 442
Reputation: 386461
It is allowed. You won't even get a warning from -Wall
or -Wextra
, though you will with -Wwrite-strings
.
It is safe as long as you don't change any of the elements of the array to which s
points (e.g. *s
or s[0]
) or try to free s
.
You'll probably run into problems if you deal with a bunch of Test
and some strings are read-only and some aren't. For example, how would you know if a string should be freed when the Test
is destroyed?
If none of your strings will be edited or freed, you could use the following to get at least a warning if you try to do something you shouldn't:
struct Test {
const char *s;
};
In the other direction, you could make a copy of the string that can be edited and/or freed.
test.s = strdup("Hey");
Upvotes: 1