C/C++获取字符数组元素个数(不推荐使用sizeof)

sizeof

sizeof是C/C++中的一个操作符,用于返回传入的数据的长度(字节数)

对于一般的元素类型来说,我们通常使用sizeof获取其长度,也习惯使用其获取数据的长度,但是如果对字符数组或者指针进行sizeof操作,往往无法得到我们预期的结果

例如:

#include <iostream>
#include <cstring>

using namespace std;

typedef struct{
int num;
char *str;
short data[2];
}sizeofTest;

int main()
{
sizeofTest *s;
s->num = 10;
s->str = "C++";
s->data[0] = 1;
s->data[1] = 2;

char str[128] = "hello";

cout << "The int len is: " << sizeof(int) << endl;
cout << "The str len(sizeof) is: " << sizeof(str) << endl;
cout << "The s len is: " << sizeof(s) << endl;
cout << "The s->str len is:" << sizeof(s->str) << endl;

cout << "The str len(strlen) is:" << strlen(str) << endl;
return 0;
}

程序运行结果如下:

C/C++获取字符数组元素个数_strlen

根据以上测试程序我们可以发现,使用sizeof获取数组和结构体指针的长度时,无法得到正确的数据

因此在获取字符串数组时,推荐使用strlen(头文件为string.h/cstring)

strlen的工作原理是检查传入的字符串,遇到’/0’则退出,返回字符串长度