Question

for debug purposes I often output pointer values (mostly this) to qDebug:

qDebug("pointer of current object = 0x%08x",this);, using "%08x" as format string and simply passing this as a parameter.

How can I convert the pointer value to a QString?

This is what I got so far:

char p = (char)this;
return QString("0x%1").arg(p, 8, '0');

But the compiler doesn't seem to figure out what to do with that value. Is casting to char correct in this case? Or what would be a safer way to do this?

Using Visual C++ with Qt 4.7.4.

EDIT

Using qulonglong as suggested

qulonglong p = (qulonglong)this;
return QString("0x%1").arg(p, 8, '0');

yields in a compiler error message (error C2666).

Was it helpful?

Solution

Using QString::arg():

MyClass *ptr = new MyClass();
QString ptrStr = QString("0x%1").arg((quintptr)ptr, 
                    QT_POINTER_SIZE * 2, 16, QChar('0'));

It will use the correct type and size for pointers (quintptr and QT_POINTER_SIZE) and will always prefix "0x".

Notes:
To prefix the value with zeros, the fourth parameter needs to be QChar('0').
To output the correct number of digits, QT_POINTER_SIZE needs to be doubled (because each byte needs 2 hex digits).

OTHER TIPS

Why not simply use QString & QString::sprintf ( const char * cformat, ... )

QString t;
// QString::sprintf adds 0x prefix
t.sprintf("%08p", ptr);

QTextStream appears to offer the functionality you seek, and operates simply on a void*.

const void * address = static_cast<const void*>(ptr);
QString addressString;
QTextStream addressStream (&addressString);
addressStream << address;
qDebug() << addressString;

Unlike the other approaches, it does not reference notions like the particular number "8" or casting to "qlonglong". Seems less worrisome, and is much like the prescribed method for std::string (though without getting std::string conversions involved)

You could do an intermediate step with sprintf:

QString pointer_to_qstring(void *ptr)
{
    char temp[16];
    sprintf(temp, "0x%08p", ptr);
    return QString(static_cast<char *>(temp));
}

Or through ostringstream:

QString pointer_to_qstring(void *ptr)
{
    std::ostringstream oss;
    oss << std::setw(8) << std::setfill('0') << std::hex << ptr:
    return QString(oss.str().c_str());
}

For me mostly it is enough to see if the pointer is the nullptror if it has the same value as an other pointer. For those cases it is enough to convert the pointer to a number and then use QString::number()

Cat * cat = new Cat();
qDebug()<<QString::number((std::uintptr_t)(cat));;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top