简体   繁体   中英

Couldn't understand the output of the program

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

int main(void) 
{
  int n,u = 0;
  printf("Enter length of word ");
  scanf("%d",&n);

  char word[n*2];
  printf("Enter the String \n");
  scanf("%s", word);
  printf("string that u have entered: %s\n",word);
  int i = n - 1, j = n;
  while(i >= 0)
  {
    printf("word[i-1] %c\n",word[i]);
    word[j] = word[i];
    printf("i %d\n",i);
    printf("j %d\n",j);
    i--;
    j++;
  }
  printf("reversed word stored at the last in the same array - %s\n",word);
}

when we give the length 3 the output doesn't give any garbage value in output but when I give greater than 3 its starts to give garbage value in the output. (yeah I know we have to add '\0' at the end of the array to stop but for length 3 without that, it works.)

Here, you have declared the word as char array and alloted the size of array. So,when you are printing via indexing of array as %c --it gives the correct result. But,at the end,when you try to print the whole 'word' char array, you used %s. Now, what %s does is: when you indicate to a string, it stores the address of the first element and keep printing the value stored in those addresses in sequential manner untill it finds the null value. So,you better use a loop to print values stored in 'word' array using %c or you can convert your char array 'word' into string & then use %s to print values inside 'word'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM