常用计算数组长度的方法
#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′