铸造指针数组(INT *为int [2]) [英] Casting pointer to Array (int* to int[2])

查看:135
本文介绍了铸造指针数组(INT *为int [2])的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何投或转换一个int *成一个int [X]

How do I cast or convert an int* into an int[x].

我想弄明白我自己,所以我做了一个快速程序,以确保我知道正是我试图把在哪里。输出是仅低于

I tried to figure it out on my own, so I made a quick program to make sure I knew exactly what I am trying to put and where. The output is just below:

Address of {type: int} &a =             0031FEF4; a = 1
Address of {type: int[2]} &b =          0031FEE4; b = 0031FEE4
Address of {type: int[2]} &b[0] =       0031FEE4; b[0] = 2
Address of {type: int[2]} &b[1] =       0031FEE8; b[1] = 3
Address of {type: int*} &c =            0031FED8; c = 008428C8
Address of {type: int*} &c[0] =         008428C8; c[0] = 2
Address of {type: int*} &c[2] =         008428D0; c[2] = 1

有一次,我确信我知道什么是在那里我尝试了一些东西。首先,我想告诉我的数组是什么将是等于code的一条线;一切我尝试失败了。然后我发现我可以做一个循环来遍历数组并访问指针,在同一时间做的事情之一元素。 是一个循环我不错,但我想知道是否有可能用较少的线路。

我如何将指针为int * C =新的INT [X] 到一个数组 INT B〔2]

How do I cast a pointer int* c = new int[x] to an array int b[2]

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

c[0] = b[0];
c[1] = b[1];
c[2] = a;

我试过了沿

b = &c[1];

这并没有明显的工作。

编辑:解决方法:
不要这样做!
如果它的必要创建指针数组,然后指向数组;这是毫无意义的任何目的,我可以捉摸。
欲了解更多详细信息,请参阅下面罗德里戈答案。

Solution: Don't do it! If it's necessary create a pointer to an array and then point to the array; this is pointless for any purposes I can fathom. For more detailed information see the answer by rodrigo below.

推荐答案

首先 B 是一个数组,而不是一个指针,所以它不是转让。

First of all b is an array, not a pointer, so it is not assignable.

此外,还可以不投任何一个数组类型。你可以,但是,转换为指针到数组。
请注意,在C和C ++指针到阵列是相当少见。它几乎总是最好使用普通的指针,或指向指针,避免指针到数组。

Also, you cannot cast anything to an array type. You can, however, cast to pointer-to-array. Note that in C and C++ pointer-to-arrays are rather uncommon. It is almost always better to use plain pointers, or pointer-to-pointers and avoid pointer-to-arrays.

不管怎样,你问问可以做,或多或少:

Anyway, what you ask can be done, more or less:

int (*c)[2] = (int(*)[2])new int[2];

的typedef 将使它更容易:

typedef int ai[2];
ai *c = (ai*)new int[2];

和是安全的,删除应该用原来的类型来完成:

And to be safe, the delete should be done using the original type:

delete [](int*)c;

如果你只是为了好玩做的这是很好的。对于现实生活中,它通常是更好地使用的std ::矢量

Which is nice if you do it just for fun. For real life, it is usually better to use std::vector.

这篇关于铸造指针数组(INT *为int [2])的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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