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.
260 is MAX_PATH
, which you're getting because sizeof
returns the size of the entire array - not just the size of the string inside the array.
To get the behavior you're looking for, use strlen
instead:
cout << "binaryPath: " << binaryPath << endl;
cout << "strlen(binaryPath): " << strlen(binaryPath) << endl;
You are confusing the size of the array with the length of the string it contains. sizeof(arrayVar)
gives you the entire size of the array regardless of how long the string it contains is. You need to use strlen()
to determine the actual length of the string it contains.
Recall that char arrays in C++ and C are used to store raw character strings, and that such strings' ending is marked by a null character.
The operator sizeof
is not dynamic: it will give you the size of the whole array, or whichever type you provide in bytes (or char, since they have the same size), as defined in your code. Hence 260 is certainly the value of MAX_PATH
, which is used to define the char array binaryPath
.
The string which is stored in that array after the call to GetModuleFilename
will be null terminated, as per the convention stated above. In order to get its length you need to count the characters in it until you reach the null char or use the strlen
function provided by the C library.
Some pointers:
- What does sizeof do?
- strlen