C++中字符数组的长度

常用计算数组长度的方法

#include <iostream>

using namespace std;

int main()
{
	char *str = "Hello World";
	cout << str << " and size = " << sizeof(str) << endl;
	for (int i = 0; i < strlen(str); i++)
	{
		cout << str[i] << " ";
	}
	cout << endl;

	int array[5] = { 1,2,3 };
	for (int i = 0; i < 5; i++)
		cout << array[i] << " ";
	cout << endl;
	cout << "The length of array = " << sizeof(array) / sizeof(array[0]) << endl;

	char string_array[6] = "hello";
	for (int i = 0; i < 6; i++)
		cout << string_array[i] << " ";
	cout << endl;
	cout << "The length of array = " << sizeof(string_array) / sizeof(string_array[0]) - 1 << endl;

	system("pause");
	return 0;
}

/*
输出:

Hello World and size = 4
H e l l o   W o r l d
1 2 3 0 0
The length of array = 5
h e l l o 
*/

字符串数组末尾有一个’\0′
cplusplus-length-char-array

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部