I have a problem casting a long to an int in c++

There is a long "biWidth" in the &pVideoInfoHeader->bmiHeader struct, I simply want to read this into an integer value "Width"

//check the video info header
Width=(int)(&pVideoInfoHeader->bmiHeader.biWidth);
Height=(int)(&pVideoInfoHeader->bmiHeader.biHeight);

//break point here

When I step through the code to the break point after the assignment and use the debugger to check the values it says "&pVideoInfoHeader->bmiHeader.biWidth | 176", which is fine, but "Width | 3253404"

Can anyone help me find out what is going on?

Edited 6 Years Ago by hanvyj: n/a

the (int) cast is from C, and is not recommended in C++ for good reasons. Use the "functional" casting:

//check the video info header
Width  = int(&pVideoInfoHeader->bmiHeader.biWidth);
Height = int(&pVideoInfoHeader->bmiHeader.biHeight);

//break point here

But in this case, long is implicitly convertable to int, so the cast is useless anyways.

hanvyj

In cases like this, I'd suggest making a short, compilable program outside of the context of your big program.

#include <iostream>

int main()
{

 long myLong = 20.3;
 std::cout << myLong << " " << (int)myLong << " " << int(myLong) << " " << static_cast<int>(myLong) << std::endl;

 return 0;
}

This should really help you understand what the expected results are. Once you know this, you should be able to more easily find the problem in your real code.

David

Thank you for both your replies, Once I tested it as you suggested, it should work. I realised that it was a pointer to a long, what a silly mistake!

Or look up the *_cast statements in C++.
e.g.
static_cast

Edited 6 Years Ago by thelamb: n/a

the (int) cast is from C, and is not recommended in C++ for good reasons. Use the "functional" casting:

//check the video info header
Width  = int(&pVideoInfoHeader->bmiHeader.biWidth);
Height = int(&pVideoInfoHeader->bmiHeader.biHeight);

//break point here

The functional cast is still the same thing as the C cast, and it has all of the same problems. The only difference is more of a constructor look in the syntax. The real C++ casts that are recommended for better code are named and specialized. In the case of explicitly casting from long to int, the static_cast operator is the recommended C++ tool.

Width = static_cast<int>(pVideoInfoHeader->bmiHeader.biWidth);
Height = static_cast<int>(pVideoInfoHeader->bmiHeader.biHeight);
This article has been dead for over six months. Start a new discussion instead.