如何通过c中的指针传递二维数组

2021-12-13 00:00:00 pointers c c++

可能的重复:
将表示二维数组的指针传递给C++中的函数

我试图通过指针将我的二维数组传递给一个函数,并想修改这些值.

I am trying to pass my 2-dimensional array to a function through pointer and want to modify the values.

#include <stdio.h>

void func(int **ptr);

int main() {
    int array[2][2] = {
        {2, 5}, {3, 6}
    };

    func(array);

    printf("%d", array[0][0]);
    getch();
}

void func(int **ptr) {
    int i, j;
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 2; j++) {
            ptr[i][j] = 8;
        }
    }
}

但是程序因此而崩溃.我做错了什么?

But the program crashes with this. What did I do wrong?

推荐答案

它崩溃是因为数组不是指向指针的指针,它会尝试读取数组值,就好像它们是指针一样,但数组只包含数据没有任何指针.
数组在内存中都是相邻的,只需接受一个指针并在调用函数时进行强制转换:

It crashes because an array isn't a pointer to pointer, it will try reading array values as if they're pointers, but an array contains just the data without any pointer.
An array is all adjacent in memory, just accept a single pointer and do a cast when calling the function:

func((int*)array);

...

void func(int *ptr) {
    int i, j;
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 2; j++) {
            ptr[i+j*2]=8;
        }
    }
}

相关文章