C++ 初始化数组指针

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6386329/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 20:01:13  来源:igfitidea点击:

C++ Initialize array pointer

c++arrayspointers

提问by somewho3

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

如何初始化指向文字数组的指针?
我希望 *grid 指向新分配的 int 数组 {1, 2, 3}。

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

thank you.

谢谢你。

采纳答案by Armen Tsirunyan

You can't initializea dynamically allocated array that way. Neither you can assignto 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

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

在您的情况下,您只能手动复制每个元素的 velue

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

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

您可以通过使用 stl 算法来避免显式循环,但想法是相同的

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

其中一些在 C++0x 中可能已经合法,我不确定。

回答by Amm Sokun

@above grid points to the address location where the first element of the array grid[] is stored. Since in C++ arrays are stored in contiguous memory location, you can walk through your array by just incrementing grid and dereferencing it.

@above grid 指向存储数组 grid[] 的第一个元素的地址位置。由于在 C++ 中数组存储在连续的内存位置,您可以通过增加网格并取消引用它来遍历数组。

But calling grid an (int*) isnt correct though.

但是调用 grid an (int*) 是不正确的。

回答by RamonBoza

Use the following code, grid is a pointer, grid[] is an element of that pointer.

使用以下代码,grid 是一个指针,grid[] 是该指针的一个元素。

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