如何通过在C指针传递一个二维数组 [英] How to pass a 2d array through pointer in c
问题描述
可能重复:结果
<一href=\"http://stackoverflow.com/questions/5329107/passing-a-pointer-re$p$psenting-a-2d-array-to-a-function-in-c\">Passing指针重新presenting一个二维数组在C ++
我试图通过指向我的2维数组传递给一个函数,要修改的值。
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;
}
}
}
这篇关于如何通过在C指针传递一个二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!