[英]Assigning literals to pointers
I know there are millions of similar question on this site, but none points to the topic I am having difficulty in understanding. 我知道这个网站上有数以百万计的类似问题,但没有人指出我难以理解的话题。
I would like to assign an integral literal to an integer pointer like this: 我想为这样的整数指针分配一个整数文字:
int *p=(int []){7} //casting the literal to array so that it would return the address of first element just like string literal.
But it gives the error: 但它给出了错误:
a parenthesized type followed by an initializer list is a non-standard explicit type conversion syntax. 括号类型后跟初始化列表是非标准显式类型转换语法。
And this code works perfectly in C. 这段代码在C中完美运行。
If this type of conversion is illegal in C++ , is there any other way to achieve the same thing? 如果这种类型的转换在C ++中是非法的,还有其他方法可以实现同样的目的吗?
The syntax 语法
int *p=(int []){7};
is supported in C99 as well C11, but not in C++. C99和C11都支持,但C ++不支持。
Options in C++11: C ++ 11中的选项:
Use a plain old array. 使用普通的旧数组。
int p[] = {7};
Use a std::array
. 使用std::array
。
std::array<int, 1> p = {7};
Use a std::vector
. 使用std::vector
。
std::vector<int> p(1, 7);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.