c++ - 将文字分配给指针

标签 c++ casting

我知道这个网站上有数百万个类似的问题,但没有一个指向我难以理解的主题。

我想像这样将整数文字分配给整数指针:

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 中的选项:

  1. 使用普通的旧数组。

    int p[] = {7};
    
  2. 使用std::array

    std::array<int, 1> p = {7};
    
  3. 使用 std::vector

    std::vector<int> p(1, 7);
    

关于c++ - 将文字分配给指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42478770/

相关文章:

c++ - 将 3D 数组传递给类(转换问题)

c#-4.0 - 如何在 C# 中将 SQLiteDataReader 值转换为 float

c - 我们如何编写 C 宏来将强制转换插入函数调用?

r - 将数据转换为整数/nu 会更改数据

java - 方法引用转换如何工作?

c - 难以理解c中的一行代码

c++ - OpenGL GLut 在 Windows 8 64 位上与 Visual Studio 2013 的链接问题

c++ - 从具有 bigendian 格式的 QByteArray 获取 float 组的有效方法

c++ - 从文本文件中读取的代码,删除停用词然后应用大小写折叠

c++ - 如何访问对象的私有(private)成员?