creativity
Member
In C, how exactly do you assign a word to a string in a struct? My professor taught how to let the user do it, but not how to hard code it.
Code:example.name[10]="John";
Something like this is what I assumed to be correct, but apparently not.
It depends on what you mean by "string." Suppose you have this:
Code:
struct strval {
char *sptr;
char buf[10];
};
Note that these struct members are different types but both conceptually represent a string.
You can initialize this struct as follows:
Code:
struct strval s = {
.sptr = "foo",
.buf = "bar"
};
This is called a designated initializer, and it's supported in GNU C and C99, but not ANSI C.
If you're assigning to a struct member, these types must be treated differently:
Code:
s.sptr = "foo";
strncpy(s.buf, "bar", sizeof(s.buf));
You need to include <string.h> for strncpy, and you also need to be aware of the fact that strncpy may truncate the input string to fit the buffer, leaving a string that is not null-terminated. This is the source of a lot of bugs, so I would suggest reading the documentation carefully.