char指针或char变量的默认值是什么 [英] what is the default value of char pointer or char variable
问题描述
下面是我尝试打印默认值/char变量&的值的代码.指针.但是在控制台上看不到它是否具有默认值或只是无法读取ASCII范围?
#include <stdio.h>
int main()
{
char c, *cp;
printf("\nValue of char c:%c\n", c);
printf("\nValue of char ptr:%c\n", *cp);
return 0;
}
惊喜!这里没有默认"值,您正在尝试未定义的行为.
详细说明,如果变量是局部范围的并且具有自动存储期限,除非显式初始化,否则存储的值是不确定的.进一步使用它会导致未定义的行为.引用C11
,第§6.7.9章
如果未自动初始化具有自动存储持续时间的对象,则其值为 不确定.[....]
-
对于第一种情况,您有一个
char
类型,如果在这种情况下,它可以具有陷阱表示形式,它将导致UB,否则它将是一个随机值. /p> -
在第二种情况下,如果您使用的是
char *
类型,则指针保存不确定的值,该值在程序上下文中为 invalid ,因此尝试取消引用该指针肯定会调用未定义的行为.
Below is the code where I am trying to print default values/values of char variable & pointer. But Can not able to see it on console.Is it has default values or just not able to read ASCII range.?
#include <stdio.h>
int main()
{
char c, *cp;
printf("\nValue of char c:%c\n", c);
printf("\nValue of char ptr:%c\n", *cp);
return 0;
}
Surprise!! there is no "default" value here, you're venturing into undefined behavior.
To elaborate, if a variable is local scoped and automatic storage duration, unless initialized explicitly, the stored value is indeterminate. Using that further, causes undefined behavior.
Quoting C11
, chapter §6.7.9
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.[....]
For the first case, where you have a
char
type, if in your case, which can have a trap representation, it'll lead to UB, otherwise, it'll be a random value.For the second case, where you have a
char *
type, the pointer holds indeterminate value, which is invalid in context of your program, so attempt to dereference the pointer surely invokes undefined behavior.
这篇关于char指针或char变量的默认值是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!