If you declare something inside a scope, it only exists inside that scope and will effectively go away as soon as that block exits.
To fix this declare it one level up, outside that immediate scope:
int a = 2;
const int LENGTH = 10; // Define the buffer length clearly
char string[LENGTH] = { 0 }; // Zero out buffer to start
if (a <= 1) {
strncpy(string, "Jahr", LENGTH - 1);
}
else {
strncpy(string, "Jahren", LENGTH - 1);
}
printf("%s", string);
Note the use of LENGTH
here as a constant so you know how big that buffer is. sizeof(string)
can work in some contexts, but if it decays to a pointer when making a function call that information is lost, so it will need to be passed in separately. It's just a good habit to get into. Changing that one value will change all places where it's used, versus having to hunt down to search and replace them all.
If you over-commit on this, it's still safe:
const int LENGTH = 10;
char string[LENGTH] = { 0 };
strncpy(string, "my spoon is too big", LENGTH - 1);
printf("%s", string);
Where here you get my spoon
as output.
Tip: Use buffer-overflow resistant functions like strncpy()
which will avoid creating a mess if you inadvertently overflow something. Using buffers that are super tiny like 10 bytes long is risky, always be generous with these unless you know specifically how they will be used.