Solved

Why is this reinterpret_cast wrong?

Posted on 2013-01-15
7
348 Views
Last Modified: 2013-01-17
ConstItems.hh
class ConstItems {
         const int getAsInt() const;

          private:
            string mValue;    
 }

ConstItems.cpp
#include "ConstItems.hh"
const int ConstItems::getAsInt() const
{
    int intVal = reinterpret_cast<int>(mValue.c_str());

    return intValue;
}

This is the compiler error:
error: cast from ‘const char*’ to ‘int’ loses precision


Why? Don't ger this.
0
Comment
Question by:prain
7 Comments
 
LVL 40

Expert Comment

by:evilrix
ID: 38780441
The standard doesn't guarantee that you can cast from a pointer to an int. This is what it actually says:

"A pointer can be explicitly converted to any integral type large enough to hold it."

In other words, the standard doesn't guarantee that an int is large enough to store a pointer. For example, on 64 bit platforms int is still quite often 32 bit and so could no be large enough to store a 64 bit pointer.

It's also worth pointing out that the only safe thing you can so with a point cast to an integral type is to cast it back to the original pointer. Any other usage is implementation defined and may or may not work as you expect (or hope).
0
 
LVL 22

Expert Comment

by:ambience
ID: 38780558
Use ptrdiff_t for safe and portable storage of simple pointers.

ptrdiff_t ConstItems::getAsInt() const
{
    ptrdiff_t intVal = reinterpret_cast<ptrdiff_t>(mValue.c_str());
    return intValue;
}
0
 
LVL 86

Accepted Solution

by:
jkr earned 100 total points
ID: 38780600
Do you want the pointer value (which I somwhow doubt) or the integer value of the string (if any)? In the latter case, you might be better off with

#include <sstream>
#include "ConstItems.hh"
const int ConstItems::getAsInt() const
{
    stringstream ss(mValue);
    int intVal;

    ss >> intVal;

   if(ss.fail()) {

       // conversion failed, not a number. Return sth. appropriate
    }

    return intValue;
}

Open in new window

0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 

Author Closing Comment

by:prain
ID: 38783219
Thanks
0
 
LVL 40

Expert Comment

by:evilrix
ID: 38784274
prain,

Just so you know, the comment that actually answered the question you asked was http:#a38780441. Generally, you should accept the comment that answered your question. Of course, if another comment was also useful there is no reason you can't split the points.

As it stands, I have no objection to leaving things as they are, but please bear that in mind for the future. Experts are motivated by the points you award them and if you skip over the actual answer to the question you asked you'll soon end up de-motivating experts.

Thanks and good luck with your project.
0
 
LVL 32

Expert Comment

by:sarabande
ID: 38786134
to add to above comments:

you may easily find out whether pointer size exceeds int size by the following:

size_t sz_cc   =  sizeof(const char *) ;
size_t sz_int  =  sizeof(int);
std::cout << "size of const char pointer is " << (int)sz_cc << std::endl;
std::cout << "size of int is " << (int)sz_int << std::endl;

Open in new window


you could assign any pointer without cast to a void *. the reverse action would need a reinterpret_cast:

void * voidptr = reinterpret_cast<int>(mValue.c_str());
...
std::string strval;
strval = reinterpret_cast<const char *>voidptr;

Open in new window


note, usage of void pointers is rareley necessary in c++. you would do it only if an existing c interface requires it. in case of a string you much better would use a fixed-sized char array for transfering the string to any which cannot use a std::string.

Sara
0
 

Author Comment

by:prain
ID: 38787208
Thanks Sara.
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now