I just run this code and what i get for n=1 is not what i expect to get. Can you explain why is this happening?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXRIGA 11
int main()
{
char s[MAXRIGA+2];
char a[MAXRIGA]="pippo";
strncpy(s, a, 1); // n=1
printf("%s", s);
return 0;
}
returns
pF
instead if n=2 or more i get what i want.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXRIGA 11
int main()
{
char s[MAXRIGA+2];
char a[MAXRIGA]="pippo";
strncpy(s, a, 2); // n=2
printf("%s", s);
return 0;
}
returns
pi
From man strncpy
:
The strncpy() function is similar, except that at most n bytes of src are copied. Warning: If there is no null byte among the first n bytes of src, the string placed in dest will not be null-terminated.
You are copying only one byte from the source string, which is not a null-terminator. So you get an undefined behavior here, as trying to print a non-terminated string. The same for n=2
, which appears to work by accident.