如果我们使用C语言中未初始化的数组会发生什么?

If we use any uninitialized array in C program, compiler will not generate any compilation and execution error i.e. program will compile and execute properly.

如果我们在C程序中使用任何未初始化的数组 ,则编译器将不会生成任何编译和执行错误,即程序将正确编译并执行。

If the array is uninitialized while declaring and even after the declaration if you do not initialize then, you may get unpredictable result.

如果数组在声明时未初始化,甚至在声明后未初始化,则可能会得到不可预测的结果。

Therefore, it is recommended to write a good and safe program you should always initialize array elements with default values.

因此,建议编写一个安全的程序,始终应使用默认值初始化数组元素。

Consider the program:

考虑该程序:

#include <stdio.h>

int main(void) 
{
	int a[5];
	int b[5] = {0};
	int c[5] = {0,0,0,0,0};

	int i; //for loop counter

	//printing all alements of all arrays
	printf("\nArray a:\n");
	for( i=0; i<5; i++ )
		printf("arr[%d]: %d\n",i,a[i]);
	
	printf("\nArray b:\n");
	for( i=0; i<5; i++)
		printf("arr[%d]: %d\n",i,b[i]);
	
	printf("\nArray c:\n");
	for( i=0; i<5; i++ )
		printf("arr[%d]: %d\n",i, c[i]);
	
	return 0;
}

Output

输出量

    Array a:
    arr[0]: -1948874610
    arr[1]: 32764
    arr[2]: 1249250789
    arr[3]: 11047
    arr[4]: 1

    Array b:
    arr[0]: 0
    arr[1]: 0
    arr[2]: 0
    arr[3]: 0
    arr[4]: 0

    Array c:
    arr[0]: 0
    arr[1]: 0
    arr[2]: 0
    arr[3]: 0
    arr[4]: 0

See the output, array a was uninitialized so the values are garbage while array b and c are initialized so the all element's values 0.

看到输出,数组a 未初始化,因此值被乱用,而数组b和c被初始化,因此所有元素的值均为0。

翻译自: https://www.includehelp.com/c/use-an-uninitialized-array-in-c.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值