Home > other >  I tried reversing a string in C without using <string.h> functions, it didn't work
I tried reversing a string in C without using <string.h> functions, it didn't work

Time:10-30

I was trying to inverse a string in c which seemed fairly easy at first but I keep encountering some weird problem that I don't seem to understand where it comes from.

The string c3 keep showing more characters that it should

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char c1[10];
    char c3[10];
    int i,j,l;

    printf("donner la chaine a inverser\n");
    fflush(stdin);
    gets(c1);

    for(i = 0; c1[i] != '\0'; i  )
    {
    }

    l = i;
    j = 0;

    for(i = l-1; i >= 0; i--)
    {
        printf("%d%d\n", i, j);

        c3[j] = c1[i];
        j  ;
    }
    
    printf("%s", c3);

    return 0;
}

I'm not really sure but c3 should only have the number of characters that c1 does but it shows that it contains more in printf("%s", c3);.

I am still new to strings in c so I probably missed something really obvious.

CodePudding user response:

The answer is quite simple. let's say your string is abcdef. in c3, you will put fedcba, where a in at index 5.

What will be at index 6 ? The answer is "no one knows". it's undefined. That's why you have garbage after your string.

In C, a string is a char array, "null terminated" ( NULL terminated means there is the character '\0' after the last character ( or simply a 0 ( not '0') ).

The simple way of solving your problem is to initialize c3 to 0.

char c3[10] = {0};

This way, your array will be filled with NULL characters.

CodePudding user response:

You did not set a null terminator at offset c3[i]. printf() will keep reading from c3 until it finds a null byte, since c3 a local object that is not initialized, printf may read and output extra characters as you experience, and potentially read beyond the end of the array which has undefined behavior.

Note also that you should not use gets() as you cannot tell this obsolete C library function the size of the destination array.

Here is a modified version:

#include <stdio.h>

int main() {
    char c1[80];
    char c3[80];
    int i, j, len;

    printf("donner la chaine a inverser:\n");
    fflush(stdin);
    if (!fgets(c1, sizeof c1, stdin))
        return 1;

    for (len = 0; c1[len] != '\0' && c1[len] != '\n'; len  )
        continue;

    for (j = 0, i = len; i-- > 0; j  ) {
        c3[j] = c1[i];
    }
    c3[j] = '\0';    // set the null terminator
  
    printf("%s\n", c3);

    return 0;
}
  • Related