我知道这个网站上有数百万个类似的问题,但没有一个指向我难以理解的主题。
我想像这样将整数文字分配给整数指针:
int *p=(int []){7} //casting the literal to array so that it would return the address of first element just like string literal.
但它给出了错误:
a parenthesized type followed by an initializer list is a non-standard explicit type conversion syntax.
这段代码在 C 中完美运行。
如果这种类型的转换在 C++ 中是非法的,是否有任何其他方法可以实现同样的目的?
最佳答案
语法
int *p=(int []){7};
C99 和 C11 都支持,但 C++ 不支持。
C++11 中的选项:
使用普通的旧数组。
int p[] = {7};
使用
std::array
。std::array<int, 1> p = {7};
使用
std::vector
。std::vector<int> p(1, 7);
关于c++ - 将文字分配给指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42478770/