I\'m trying to understand how to solve this trivial problem in C, in the cleanest/safest way. Here\'s my example:
#include
int main(int argc
Think of strings as abstract objects, and char arrays as containers. The string can be any size but the container must be at least 1 more than the string length (to hold the null terminator).
C has very little syntactical support for strings. There are no string operators (only char-array and char-pointer operators). You can't assign strings.
But you can call functions to help achieve what you want.
The strncpy()
function could be used here. For maximum safety I suggest following this pattern:
strncpy(p.name, "Jane", 19);
p.name[19] = '\0'; //add null terminator just in case
Also have a look at the strncat()
and memcpy()
functions.