简体   繁体   English

无法理解程序的 output

[英]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.当我们给出长度 3 时,output 在 output 中没有给出任何垃圾值,但是当我给出大于 3 时,它开始在 Z78E6221F6393D1356681DB398F14CED6 中给出垃圾值。 (yeah I know we have to add '\0' at the end of the array to stop but for length 3 without that, it works.) (是的,我知道我们必须在数组末尾添加 '\0' 才能停止,但如果没有它,长度为 3,它可以工作。)

Here, you have declared the word as char array and alloted the size of array.在这里,您已将单词声明为 char 数组并分配了数组的大小。 So,when you are printing via indexing of array as %c --it gives the correct result.因此,当您通过将数组索引为 %c 进行打印时,它会给出正确的结果。 But,at the end,when you try to print the whole 'word' char array, you used %s.但是,最后,当您尝试打印整个 'word' 字符数组时,您使用了 %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.现在,%s 所做的是:当您指示字符串时,它会存储第一个元素的地址并按顺序继续打印存储在这些地址中的值,直到找到 null 值。 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'.因此,您最好使用循环打印存储在 'word' 数组中的值,使用 %c 或者您可以将 char 数组 'word' 转换为字符串,然后使用 %s 打印 'word' 中的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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