C ++初始化数组指针 [英] C++ Initialize array pointer

查看:183
本文介绍了C ++初始化数组指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何初始化一个指针数组常量?结果
我想*格指向新分配的int数组{1,2,3}

How do I initialize a pointer to a literal array?
I want *grid to point to the new allocated int array {1, 2, 3}.

int *grid = new int[3];
*grid = {1, 2, 3};

感谢您。

推荐答案

您不能的初始化的动态分配的数组的方式。你也不能的分配的以这种方式数组(动态或静态)。在初始化静态数组,即这种语法才有效。

You can't initialize a dynamically allocated array that way. Neither you can assign to an array(dynamic or static) in that manner. That syntax is only valid when you initialize a static array, i.e.

int a[4] = {2, 5, 6, 4};

我的意思是,即使下面是非法的:

What I mean is that even the following is illegal:

int a[4];
a = {1, 2, 3, 4}; //Error

在你的情况,你可以做什么,但通过手工复制的每个元素的velue

In your case you can do nothing but copy the velue of each element by hand

for (int i = 1; i<=size; ++i)
{
    grid[i-1] = i;
}

您可能会避免外在的循环使用STL算法,但想法是一样的。

You might avoid an explicit loop by using stl algorithms but the idea is the same

其中一些可能已经成为C ++ 0x中的法律,我不知道。

Some of this may have become legal in C++0x, I am not sure.

这篇关于C ++初始化数组指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆