如何将malloc返回的指针视为多维数组? [英] How to treat a pointer returned by malloc as a multidimensional array?

查看:63
本文介绍了如何将malloc返回的指针视为多维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法告诉编译器我分配了一个大小为N * M的内存,而我想将此指针视为N * M数组?换句话说,有没有办法写这样的东西?:

Is there a way to tell the compiler that I've allocated a memory of size N * M and I wanna treat this pointer as N * M array? In other words, is there a way to write something like this?:

int arr[N][M] = (int[N][M])malloc(N * M * sizeof(int));
arr[x][y] = 123;

我知道编译器不知道数组的维数,只知道那是一个指针.所以我的问题是:我能以某种方式告诉编译器,malloc返回的指针是一个数组指针,它的维数是N * M吗?我可以使用指向指针的数组,指向数组的指针或指向指针的指针,但是在所有情况下,我都必须查找2个地址.我想在堆上有一个连续的内存,并将其视为多维数组.就像我写的那样:

I know that the compiler doesn't know the dimensions of the array, all it knows is that that's a pointer. so my question is: can I somehow tell the compiler that this pointer returned by malloc is an array pointer and it's dimensions are N * M? I can use an array to pointers, pointer to arrays or pointer to pointers, but in all cases I'll have to lookup 2 addresses. I want to have a contiguous memory on the heap and treat it as a multidimensional array. just like how I would write:

int arr[N][M];

有什么方法可以实现?

推荐答案

在C ++程序中,应使用运算符new.

In a C++ program you should use the operator new.

对于malloc,如果要分配二维数组,则在C ++中M是常量表达式.

As for malloc then in C++ M shall be a constant expression if you want to allocate a two-dimensional array.

您可以编写示例

int ( *arr )[M] = ( int ( * )[M] )malloc( N * M * sizeof(int) );

int ( *arr )[M] = ( int ( * )[M] )malloc( sizeof( int[N][M] ) );

如果要使用new运算符,则分配看起来像

If to use the operator new then the allocation can look like

int ( *arr )[M] = new int[N][M];

如果M不是编译时常量,则可以使用标准容器std::vector,如下面的演示程序中所示

If M is not a compile-time constant then you can use the standard container std::vector as it is shown in the demonstrative program below

#include <iostream>
#include <vector>

int main() 
{
    size_t n = 10, m = 10;

    std::vector<std::vector<int>> v( n, { m } );

    return 0;
} 

这篇关于如何将malloc返回的指针视为多维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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