C++ 获取数组和指针(所指字符串)的长度
#include <iostream>
#include <string.h>
using namespace std;
void getPointerLen(char *str) {
int len = strlen(str);
cout << len << endl;
}
void getStringLen(char str[]) {
int len = sizeof(str) / sizeof(str[0]);
cout << len << endl;
}
int main() {
char str[] = "hello world!";
getPointerLen(str); //不算结尾的'/0'
int len = sizeof(str) / sizeof(str[0]); //算结尾的'/0'
cout << len << endl;
return 0;
}
结果:
12
13