C++ sizeof运算符用于数组
一些学习心得
- 如果将sizeof用于数组名,得到的将是整个数组中的字节数
- 如果将sizeof用于数组元素,得到的将是元素的长度
- 字符串数组是char数组,但char数组不一定是字符串;以空字符(\0)结尾的是字符串
- 字符串数组的长度不要忘记结尾的空字符(\0)
- 数组名即数组第一个元素的地址
#include <iostream>
#include <string>
using namespace std;
int main()
{
char str[]="Hello World!"; //字符串char数组
for (int i=0; i<sizeof(str); ++i){cout << str[i];} //数组从0开始编号
cout << endl;
cout << "sizeof(str) = " << sizeof(str) << endl; //字符串数组的长度不要忘记结尾的空字符(\0)
int a[]={3,4,5,6,7,8};
cout << "a = " << a << endl; //数组名即数组第一个元素的地址
cout << "&a[0] = " << &a[0] << endl;
cout << "sizeof(a) = " << sizeof(a) << endl; //如果将sizeof用于数组名,得到的将是整个数组中的字节数
cout << "a[0] = " << a[0] << endl; //如果将sizeof用于数组元素,得到的将是元素的长度
cout << "sizeof(a[0]) = " << sizeof(a[0]) << endl;
cout << "sizeof(int) = " << sizeof(int) << endl;
cout << "sizeof(float) = " << sizeof(float) << endl;
cout << "sizeof(double) = " << sizeof(double) << endl;
return 0;
}
运行结果: