简体   繁体   English

在C ++中用Char *制成std :: string

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

OSX 10.8, Carbon OSX 10.8,碳纤维

I have a std::string that I want to derive from a Char* 我有一个想要从Char *派生的std :: string *

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. 您对星号过于宽容-通常不需要指向CFStringRef的指针,并且您的数组实际上是一个指针数组,这不是您想要的。

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: 如果cchar* ,则可以进行以下操作:

g_uid.assign(c, size);

The problem is that c isn't char* , it's an array of 128 char* s: 问题是c不是char* ,它是128个char* s的数组:

char *c[128];

This is a common beginners mistake in C/C++. 这是C / C ++中常见的初学者错误。 I remember making this same mistake back in the day. 我记得在同一天犯了同样的错误。 A declaration like char *c[128]; char *c[128];这样的声明char *c[128]; isn't giving you an array of 128 characters as you might be led to believe. 可能会导致您相信,但没有提供128个字符的数组。 Its actually giving you an array of 128 pointers to char s. 实际上,它为您提供了一个指向char的128个指针的数组。 You don't want that. 你不要那样

You want to declare an array of 128 chars which looks like: 您要声明一个128个字符的数组,如下所示:

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. 现在,您可能不认为cchar*因为您看不到任何*但是在每次声明某物数组时,该变量将自动成为您指定的任何类型的指针。 It actually points to the address of the very first element of the array. 它实际上指向数组的第一个元素的地址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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