返回一个2D数组或一个指针

返回一个2D数组或一个指针

本文介绍了返回一个2D数组或一个指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在函数内创建2d数组 int 2DRepresentation [mapWidth] [mapHeight]; ,返回此值的最佳方法是什么?

If a 2d array is created int 2DRepresentation[mapWidth][mapHeight]; inside a function, what is the best way to return this?

函数返回的外观如何?

宁愿创建指向2d数组的指针并将其传递到函数中,还是更可取的,在功能内对其进行修改?如果是这样,指向2D数组的指针的外观如何?像这样:

Would it be preferred to rather create a pointer to a 2d array and pass it into a function, modifying it within the function? If so, how does a pointer to a 2D array look? Like this:

int * 2DRepresentation [mapWidth] [mapHeight];

接受2d数组指针的函数参数看起来如何?

How would the function parameter look like which accepts a 2d array pointer?

推荐答案

返回数组的基地址,即 Pointer 。但是,唯一的解决方案是必须使数组 static 成为静态数组,否则一旦函数超出范围,它将被销毁。如果不想使其变为静态,则应使用动态内存分配

You will have to return the base address of the array, i.e., a Pointer. However the only solution is that you will have to make the array static otherwise once the function goes out of scope, it will get destroyed. If you don't want to make it static you should use dynamic memory allocation.

样本伪代码:

    int **array; // array is a pointer-to-pointer-to-int
    array = malloc(mapHeight * sizeof(int *));
    if(array == NULL)
        {
        fprintf(stderr, "out of memory\n");
        exit or return
        }
    for(i = 0; i < mapHeight ; i++)
        {
        array[i] = malloc(mapWidth * sizeof(int));
        if(array[i] == NULL)
            {
            fprintf(stderr, "out of memory\n");
            exit or return
            }
        }

这是您的方式可能会将其传递给名为 foo 的函数,说:

This is how you might pass it into a function named foo say:

foo(int **array, int _mapHeight, int _mapWidth)
    {
    }

数组衰减为指针,因此您需要将行和列值作为单独的参数传递。

Arrays decay into pointers, hence you need to pass the rows and column values as separate arguments.

这篇关于返回一个2D数组或一个指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 19:45