2
#include <stdio.h>
#include <stdlib.h>

int main()
{
    char s[40]="Who are you tell me that I can not code?";
    char c=s[8];
    char st[2];
    st[0]=s[0],st[1]=s[1];
    printf("%s \n",st);
    return 0;
}

Why is it printing my original string 's' also when I'm printing st?

Output:-

WhWho are you tell me that I can not code?►

Process returned 0 (0x0)   execution time : 0.048 s
Press any key to continue.
  • 2
    Do you know what a [null terminator](https://stackoverflow.com/questions/4418708/whats-the-rationale-for-null-terminated-strings) is? Well, your `st` string doesn't have one. – Adrian Mole Jun 11 '22 at 13:01
  • … basically meaning `printf` doesn’t know when to stop printing. Therefore carries on in memory until a null terminator is found. – S3DEV Jun 11 '22 at 13:05

1 Answers1

2

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;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189