s
is not a proper C string because it has exactly 40 bytes and 40 characters. C strings must have a null terminator byte. You should define it as:
char s[] = "Who are you tell me that I can not code?";
There is the same problem for st
that you define as an array of 2 bytes where you store 2 characters. You should define st
as an array of 3 bytes and set a '\0'
null character at st[2]
.
Both of these problems can cause undefined behavior. and the second does as you pass st
to printf()
for a %s
format which expects a proper C string pointer.
Here is a modified version:
#include <stdio.h>
int main() {
char s[] = "Who are you tell me that I can not code?";
char st[3];
st[0] = s[0];
st[1] = s[1];
st[2] = '\0';
printf("%s\n", st);
return 0;
}
Note that you can also print a substring with printf
using the precision field:
#include <stdio.h>
int main() {
char s[] = "Who are you tell me that I can not code?";
// print the 3 characters at offset 4
printf("%.3s\n", st + 4);
return 0;
}