Can't output int as result of sizeof()

不问归期 提交于 2019-12-11 13:36:15

问题


I'm lloking to write a program in C++ which will sync two directories for me, and for part of it I need to get the size of an char array. The code I'm using is below

#include <iostream>
#include <Windows.h>
using namespace std;

int main() {
    char binaryPath[MAX_PATH];
    GetModuleFileName(NULL, binaryPath, MAX_PATH);
    int r = sizeof(binaryPath);

    return 0;
}

Anyway, that code compiles and runs fine. The problem comes when I try and cout the binaryPath variable. In the main block, after the assignment/declaration of r if I try to output r to screen like so

cout << r;

the binary stops running. Windows says "Cpp.exe" has stopped working, and I am forced to force close the program. I have absolutely no idea why.

Even if I try much simpler versions, like the program below

#include <iostream>
using namespace std;
int main() {
    int r = 7;
cout << sizeof(r);
return 0;
}

the result is the same. It seems to me that I can pretty much do what I want with sizeof() behind the scenes, but as soon as I try and output it stuff stops working.

I'm using MinGW on a mac running windows 8 (b/c win8 has caused me some troubles in the past, not sure if it's managed to break c++).

Help is sorely needed and appreciated.

Thanks!


回答1:


sizeof() will give you the size of the object. That is MAX_PATH, not the length of the string inside it. Use strlen for that.




回答2:


Reinstall MinGW. That worked for me. Make sure to run the setup as admin though



来源:https://stackoverflow.com/questions/16049936/cant-output-int-as-result-of-sizeof

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!