繁体   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);
}

当我们给出长度 3 时,output 在 output 中没有给出任何垃圾值,但是当我给出大于 3 时,它开始在 Z78E6221F6393D1356681DB398F14CED6 中给出垃圾值。 (是的,我知道我们必须在数组末尾添加 '\0' 才能停止,但如果没有它,长度为 3,它可以工作。)

在这里,您已将单词声明为 char 数组并分配了数组的大小。 因此,当您通过将数组索引为 %c 进行打印时,它会给出正确的结果。 但是,最后,当您尝试打印整个 'word' 字符数组时,您使用了 %s。 现在,%s 所做的是:当您指示字符串时,它会存储第一个元素的地址并按顺序继续打印存储在这些地址中的值,直到找到 null 值。 因此,您最好使用循环打印存储在 'word' 数组中的值,使用 %c 或者您可以将 char 数组 'word' 转换为字符串,然后使用 %s 打印 'word' 中的值。

暂无
暂无

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

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