为什么C程序中的输出不同 [英] Why is the output different in C program

查看:91
本文介绍了为什么C程序中的输出不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  #include   <   stdio.h  >  
#include < conio.h >
void main()
{
clrscr();
char a [ 3 ] = lk;
printf( %c,a [ 3 ]);
getch();
}





而不是将lk作为输出,我得到输出为埃(A ^ 0)。我不明白我是怎么得到的。请帮帮我。谢谢。



[由Jochen Arndt编辑:添加代码格式]

解决方案

如果要打印一个字符串,你必须使用 printf 格式字符作为'%s'的字符串并将指针传递给字符串:

 printf( %s,a); 



您打印的单个字符也不是字符串的一部分 a

 a [ 0 ] = '  l'; 
a [ 1 ] = ' k'< /跨度>;
a [ 2 ] = 0 ; // NULL终止字符
// a [3] =?未定义,因为它超出范围


您的char表的长度为3,并且您尝试访问数组边界外的值。有效索引是0,1和2,但因为您使用char数组,最后一个值 a [2] 用于存储字符串的结尾(NULL值)

#include<stdio.h>
#include<conio.h>
void main()
{       
    clrscr();
    char a[3]="lk";
    printf("%c",a[3]);
    getch();
}



Instead of getting lk as output, I get the output as angstrom(A^0). I don't understand how I get this.Please help me. Thanks.

[Edit by Jochen Arndt: Added code formatting]

解决方案

If you want to print a string you must use the printf format character for strings which is '%s' and pass the pointer to the string:

printf("%s",a);


You are printing a single character which is nor part of your string a:

a[0] = 'l';
a[1] = 'k';
a[2] = 0; // The NULL termination character
//a[3] = ? Undefined because this is out of bound


Your char table has length of 3, and you are trying to access value outside the array boundary. The valid indexes are 0, 1, and 2, but because you are using char array the last value a[2] is used to store the end of string (NULL value).


这篇关于为什么C程序中的输出不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆