正在将指针强制转换为数组(int*到int[2])
Casting pointer to Array (int* to int[2])
如何将int*强制转换或转换为int[x]?
首先,我知道指针可以被索引。所以我知道我可以循环指针和数组,并手动转换指针。(例如,具有arr[i] = p[i]
的for循环)。我想知道是否可以在更少的代码行中实现同样的结果。
作为一个例子,我尝试将指针int* c = new int[x]
投射到数组int b[2]
int a = 1;
int b[2] = { 2, 3 };
int* c = new int[b[1]];
c[0] = b[0];
c[1] = b[1];
c[2] = a;
我想看看值在哪里,所以我制作了一个简单的程序来输出地址和值。输出如下:
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
有一次,我确定我知道我在哪里尝试了一些东西。想到的第一个想法是获取指针分配的第二个元素的地址,然后用它替换数组的内存地址(请参阅下面的代码)。我所做的一切尝试最终都失败了,通常都是语法错误。
这就是我尝试过的我真的很想这样做,因为这将是最简单的解决方案。
b = &c[1];
这显然没有奏效。
编辑:解决方案:不要这么做如果有必要创建一个指向数组的指针,然后指向该数组;这对我所能理解的任何目的来说都毫无意义。有关更多详细信息,请参阅下面罗德里戈的回答。
首先,b
是一个数组,而不是指针,因此它是不可赋值的。
此外,不能将任何内容强制转换为数组类型。但是,您可以强制转换为指向数组的指针。请注意,在C和C++中,指向数组的指针并不常见。使用纯指针,或者指针对指针,避免指针对数组,几乎总是更好的。
不管怎样,你的要求或多或少都可以实现:
int (*c)[2] = (int(*)[2])new int[2];
但typedef
会让它变得更容易:
typedef int ai[2];
ai *c = (ai*)new int[2];
为了安全起见,删除应该使用原始类型:
delete [](int*)c;
如果你只是为了好玩,那就太好了。在现实生活中,通常最好使用std::vector
。
尽管不能重新分配数组标识符。。有时,你所做的事情的精神允许你简单地创建一个引用,并将自己伪装成一个数组注意:这只是罗德里戈答案的一个轻微扩展。。。值得一提的是,无论任务是什么,都可能有更好的方法来完成
#include <iostream>
int main() {
int x[1000] = {0};
for(int i = 0; i < 10; ++i) {
int (&sub_x)[100] = *(int(*)[100])(&x[i*100]);
//going right to left basically:
// 1. x[i*100] -- we take an element of x
// 2. &x[N] -- we take the address of the element
// 3. (int(*)[100]) -- we cast it to a pointer to int[100]
// 4. *(...) -- lastly we dereference the pointer to get an lvalue
// 5. int (&sub_x)[100] -- we create the reference `sub_x` of type int[100]
for(int j = 0; j < 100; ++j) {
sub_x[j] = (i*100)+j;
}
}
for(int i = 0; i < 1000; ++i) {
if(i != 0) {
std::cout << ", ";
}
std::cout << x[i];
}
std::cout << std::endl;
}
正如你所期望的,输出最终只打印0-999,没有间隙
输出:
0, 1, 2, ..., 999
- 按字符值访问int数组
- 将 int 数组转换为 std::vector<int*>
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- 整数区间(或 int 数组)中每个数字的出现次数
- Int 数组到C++容器
- C++ 未初始化的本地(非全局)int 数组中的元素类型到底是什么?
- 如何检测将文本文件读入 int 数组的新行
- C++快速将 int 数组内容转储到文本文件中
- <string> 如何在使用 SWIG 时将 int 数组和 List 作为参数传递给 C# C++
- 如何制作不允许重复值的 C++ int 数组循环?
- 如何将逗号分隔的文件读取为 2D int 数组?
- int 数组,但索引是字符?
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 将 int 数组转换为带有小数C++的双精度数组
- 将双精度值分配给 int 数组时的类型转换
- 已编辑 我如何将其拆分为 char 和 int 数组
- 从 C++ 中的 int ** 数组访问元素
- C++程序无法分配 int 数组?
- 我正在编写一个代码来将 int 数组存储在文件中,然后用 c++ 检索它,但是检索第一项是假值,我该如何解决这个问题?
- 如何通过头文件中的函数初始化 const int 数组?