Solved

Why is this reinterpret_cast wrong?

Posted on 2013-01-15
7
354 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
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 

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 33

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

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
mixing C++ & C# in Vis Studio 2013 7 197
Unresolved External Symbols 3 101
C++ :Change value from  DisableCMD registry 4 65
Why  my code (program) build with old compiler? 11 75
Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

808 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