C++ – How to calculate the number of elements in a char array

ccharsizeofstringwindows

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!

Best Answer

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;