正在将指针强制转换为数组(int*到int[2])

Casting pointer to Array (int* to int[2])

本文关键字:int 数组 指针 转换      更新时间:2023-10-16

如何将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