-4

I was writing a program to reverse an entered string in C and my code is :

#include<stdio.h>
#include<string.h>
void main()
{
    int sz;
    printf("Enter the size of the string : ");
    scanf("%d",&sz);
    char str[sz];
    gets(str);
    printf("Enter the string : \n");
    gets(str);
    char str1[sz];
    int i =0;
    --sz;
    for(i=0;i<=sz;i++)    
    {
          str1[sz-i]=str[i];

    }
    printf("%s",str1);
}

well this program is giving an weird output for string sizes 8,9 and 10 for size 8 the reversed string is being printed followed by a space and 2 garbage characters,for size 9 the reversed string is being printed followed by 2 garbage characters and for size 10 the reversed string is being printed by a garbage character and for other string sizes the program is running properly. why is this happening?

1 Answers1

0

Note:

  • It is not smart to try to limit the input string by asking the user, the user can still write string with length greater/ less
  • Reading string from console does by default not allow spaces

First option:
Read a string of a static size:

 char original[5];
 scanf("%5s", original); // String containing 5 chars

Second option:
Read a string of variable size:

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

// Length of String
unsigned expected;

printf("Enter the length of the string: ");
scanf("%u", &expected);

char *temp; // Warning: Uninitialized

// Get string
printf("Enter the string: ");
scanf("%s", temp);

unsigned actual = strlen(temp);
unsigned length = actual > expected ? expected : actual;

char *string = (char *) malloc(length * sizeof(char));
char *reverse = (char *) malloc(length * sizeof(char));

 // Trim string to proper size
for (int i = 0; i < length; i++) {
  string[i] = temp[i];
}

// Reverse string
for (int i = 0, j = length - 1; i <= j; i++) {
  reverse[i] = string[j - i];
}

// Print Strings
printf("%s", string);
printf("\n%s", reverse);