如何计算char数组中的元素数? [英] How can I calculate the number of elements in a char array?
问题描述
我试图计算数组中元素的数量,并被告知该行
int r = sizeof (array)/ sizeof(array [0])
会给我数组中元素的数量。而且我发现该方法确实有效,至少对于int数组有效。但是,当我尝试此代码时,事情就坏了。
#include< iostream>
#include< Windows.h>
使用命名空间std;
int main(){
char binaryPath [MAX_PATH];
GetModuleFileName(NULL,binaryPath,MAX_PATH);
cout<< binaryPath:<< binaryPath<<恩德尔
cout<< sizeof(binaryPath):<< sizeof(binaryPath)<<恩德尔
cout<< sizeof(binaryPath [0]:<< sizeof(binaryPath [0])<< endl;
返回0;
}
当此程序运行binaryPath时,值是
C:\用户\Anish\工作区\CppSync\调试\CppSync.exe
似乎由sizeof(以字节为单位?位?idk,有人可以解释吗?)返回的大小为260。
sizeof(binaryPath [0]);
的值为1。 / p>
很明显,然后将260除以1得到的结果是260,这不是数组中元素的数量(据我的估计,这是42个左右),有人可以解释一下我做错了吗?
我有一个偷偷的怀疑,实际上并不是我所想到的数组(我来自Java和python),但是我m不确定,所以我要问你们。
谢谢!
如果您正在寻找字符串的大小那么您需要使用 strlen
,如果您使用 sizeof
,它将告诉您分配的金额而不是空终止字符串的大小:
std :: cout<< strlen(binaryPath:<< strd :: endl;
您需要在顶部添加 #include< cstring>
。
I was trying to calculate the number of elements in an array, and was told that the line
int r = sizeof(array) / sizeof(array[0])
would give me the number of elements in the array. And I found the method does work, at least for int arrays. When I try this code, however, things break.
#include <iostream>
#include <Windows.h>
using namespace std;
int main() {
char binaryPath[MAX_PATH];
GetModuleFileName(NULL, binaryPath, MAX_PATH);
cout << "binaryPath: " << binaryPath << endl;
cout << "sizeof(binaryPath): " << sizeof(binaryPath) << endl;
cout << "sizeof(binaryPath[0]: " << sizeof(binaryPath[0]) << endl;
return 0;
}
When this program runs binaryPath's value is
C:\Users\Anish\workspace\CppSync\Debug\CppSync.exe
which seems to have a size returned by sizeof (in bytes? bits? idk, could someone explain this too?) of 260. The line
sizeof(binaryPath[0]);
gives a value of 1.
Obviously then dividing 260 by one gives a result of 260, which is not the number of elements in the array (by my count it's 42 or so). Could someone explain what I'm doing wrong?
I have a sneaking suspicion that isn't actually an array as I think of it (I come from Java and python), but I'm not sure so I'm asking you guys.
Thanks!
If you are looking for the size of the string then you need to use strlen
, if you use sizeof
it will tell you the allocated amount not the size of the null terminated string:
std::cout << "strlen(binaryPath: " << strlen(binaryPath) << std::endl;
You will need to add #include <cstring>
on the top.
这篇关于如何计算char数组中的元素数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!