Home > Mobile >  Why my substring is not being saved in 'st1' in a for loop but when I'm trying to pri
Why my substring is not being saved in 'st1' in a for loop but when I'm trying to pri

Time:06-12

Why in the for loop the value of st1 is not saved ie: when I'm printing st1 nothing is being printed?

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

int main() {
    char s[40] = "Who are you to tell me that I can not code?";
    char st1[15];

    for (int i = 2; i < 9; i  ) {
        st1[i] = s[i];
        printf("%c", s[i]);
    }
    printf("\n Now Printing the Whole at once \n");
    printf("%s", st1);
    return 0;
}

Here is the Output.....

o are y
 Now Printing the Whole at once

Process returned 0 (0x0)   execution time : 0.052 s
Press any key to continue.

CodePudding user response:

In your code st[0] and st[1] are never set, so printing the string with printf has undefined behavior. st[0] probably happens to be a null byte, so printf prints nothing.

You should use a different index into st1 and set a null byte at the end.

Beware also that s is not null terminated either because it has exactly 40 characters so no space for a null terminator byte.

Here is a modified version:

#include <stdio.h>

int main() {
    char s[] = "Who are you to tell me that I can not code?";
    char st1[15];
    int j = 0;
    for (int i = 2; i < 9; i  ) {
        st1[j  ] = s[i];
        printf("%c", s[i]);
    }
    st1[j] = '\0';

    printf("\nNow Printing the whole at once\n");
    printf("%s\n", st1);
    return 0;
}

CodePudding user response:

This loop

for (int i = 2; i < 9; i  ) {
    st1[i] = s[i];

reads from s at indices [2, 8], but also writes to st1 at indices [2, 8]. This means indices [0, 1] and [9, 14] of st1 contain indeterminate values, having never been initialized. Reading these values is a form of undefined behaviour.

Use a separate index to place values from the start of st1, and make sure to null-terminate the result.

int j = 0;

for (int i = 2; i < 9; i  ) {
    st1[j  ] = s[i];
    printf("%c", s[i]);
}

st1[j] = '\0';

Aside: this initializer, being of type char [44], is too long for the array being initialized.

char str[40] = "Who are you to tell me that I can not code?";
XXX.c:5:18: warning: initializer-string for char array is too long
    char s[40] = "Who are you to tell me that I can not code?";
                 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Use an empty size declarator to have the array automatically sized to match its initializer.

char str[] = "Who are you to tell me that I can not code?";
  • Related