简体   繁体   中英

Making a std::string out of a Char* in C++

OSX 10.8, Carbon

I have a std::string that I want to derive from a Char*

Example:

CFStringRef *s;
char *c[128];

CFStringGetCString(*s, *c, 128, kCFStringEncodingUTF8);

int size = sizeof(c);
g_uid.assign(c, size);

But I am getting an invalid conversion and I dont understand why

error: invalid conversion from 'char**' to 'long unsigned int'

std::string g_uid = ""; is defined as a global

You're too generous with the asterisks - you generally don't need a pointer to CFStringRef , and your array is actually an array of pointers, which is not what you want.

It should look more like this:

CFStringRef s;
char c[128];

if (CFStringGetCString(s, c, 128, kCFStringEncodingUTF8))
{
    g_uid = c;
}
else
{
     // 128 characters wasn't enough.
}

If c where a char* , the following would work:

g_uid.assign(c, size);

The problem is that c isn't char* , it's an array of 128 char* s:

char *c[128];

This is a common beginners mistake in C/C++. I remember making this same mistake back in the day. A declaration like char *c[128]; isn't giving you an array of 128 characters as you might be led to believe. Its actually giving you an array of 128 pointers to char s. You don't want that.

You want to declare an array of 128 chars which looks like:

char c[128];

Now you might not think that c was a char* because you don't see any * s but any time you declare an array of something, that variable is automatically a pointer of whatever type you specify. It actually points to the address of the very first element of the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM