C++数组赋值

情况1:无{}

如果没有初始化函数中定义的数组,则其元素将是不确定的,这意味着元素的值为以前驻留在该内存单元中的值。

int

#include<iostream>
using namespace std;
int main()
{
	int a[5];
	a[1] = 2;
	for (int i : a)
	{
		cout << i <<" ";
	}
	system("pause");
	return 0;
}

//输出:-858993460 2 -858993460 -858993460 -858993460

char 【-52可以理解为乱码】

#include<iostream>
using namespace std;
int main()
{
	char a[5];
	a[1] = '2';
	for (int i : a)
	{
		cout << i <<" ";
	}
	system("pause");
	return 0;
}
//输出:-52 50 -52 -52 -52

情况2: 有{}

int

#include<iostream>
using namespace std;
int main()
{
	int a[5] = {};
	a[1] = 2;
	for (int i : a)
	{
		cout << i <<" ";
	}
	system("pause");
	return 0;
}
//输出: 0 2 0 0 0

char

#include<iostream>
using namespace std;
int main()
{
	char a[5] = {};
	a[1] = '2';
	for (char i : a)
	{
		if (i == '\0')
			cout <<"a"<<" ";
		cout <<i<<" ";
	}
	system("pause");
	return 0;
}
输出:a   2 a   a   a

总结:加个={}没有坏处,防止乱码

    int a[4];
    int b[4] = { 0 };
    cout << sizeof a << '\n' <<sizeof b<<endl;

试了一下内存空间,其实在声明时不管有没有初始化都已经分配内存空间了,结果都是16.

猜你喜欢

转载自blog.csdn.net/qq_40801709/article/details/106872713
今日推荐