通过将指针传递给c中的函数来创建2D数组

时间:2016-04-20 12:58:04

标签: c arrays function pointers malloc

所以我读了几十个将2D数组指针传递给函数以在函数中获取/更改该数组值的示例。但是可以在函数内创建(分配内存)。像这样:

#include <stdio.h>

void createArr(int** arrPtr, int x, int y);

int main() {

    int x, y;       //Dimension
    int i, j;       //Loop indexes
    int** arr;      //2D array pointer
    arr = NULL;
    x=3;
    y=4;

    createArr(arr, x, y);

    for (i = 0; i < x; ++i) {
        for (j = 0; j < y; ++j) {
            printf("%d\n", arr[i][j]);
        }
        printf("\n");
    }
    _getch();    
}

void createArr(int** arrPtr, int x, int y) {
    int i, j;       //Loop indexes
    arrPtr = malloc(x*sizeof(int*));
    for (i = 0; i < x; ++i)
        arrPtr[i] = malloc(y*sizeof(int));

    for (i = 0; i < x; ++i) {
        for (j = 0; j < y; ++j) {
            arrPtr[i][j] = i + j;
        }
    }    
}

3 个答案:

答案 0 :(得分:3)

忘记指针指针。它们与2D阵列无关。

如何正确执行:How do I correctly set up, access, and free a multidimensional array in C?

使用指针指针错误的原因之一:Why do I need to use type** to point to type*?

如何正确执行此操作的示例:

int positionOfMenuItem = 0; //or any other postion
MenuItem item = menu.getItem(positionOfMenuItem);
SpannableString s = new SpannableString(settingsItemTitle);
s.setSpan(new AlignmentSpan.Standard(Alignment.ALIGN_CENTER), 0, s.length(), 0);

item.setTitle(s);

答案 1 :(得分:2)

是的,将指针传递给int **(但是3星被认为是坏的样式),我建议从函数中返回一个已分配的变量:

int **createArr(int x, int y)
{
    int **arrPtr;
    int i, j;       //Loop indexes

    arrPtr = malloc(x*sizeof(int*));
    if (arrPtr == NULL) { /* always check the return of malloc */
        perror("malloc");
        exit(EXIT_FAILURE);
    }
    for (i = 0; i < x; ++i) {
        arrPtr[i] = malloc(y*sizeof(int));
        if (arrPtr[i] == NULL) {
            perror("malloc");
            exit(EXIT_FAILURE);
        }
    }
    for (i = 0; i < x; ++i) {
        for (j = 0; j < y; ++j) {
            arrPtr[i][j] = i + j;
        }
    }
    return arrPtr;   
}

使用以下方式调用:

arr = createArr(x, y);

答案 2 :(得分:0)

是的,可以通过这种方式初始化数组。只要传递指针,内存地址应保持不变。因此,如果您为指针指定任何内容,它将有效。

将a []视为指向第一个元素的*指针

a [] []将是指向第一个元素的指针的**指针或指向第一个数组的指针(表的第一行)

相关问题