指针的指针传参问题C/C++ code#include stdio.hvoid Init(int*** p, int wWide, int wHigh)int main(vo
指针的指针传参问题
C/C++ code#include <stdio.h>void Init(int*** p, int wWide, int wHigh);int main(void){ int **p = NULL; Init(&p, 5, 4); return 0;}void Init(int*** p, int wWide, int wHigh){ int h = 0; int w = 0; int i = 1; if (*p == NULL) { *p= (int**)malloc(wHigh * sizeof (int*)); for (h = 0; h < wHigh; ++h) { *p[h] = (int*)malloc(wWide * sizeof (int)); for (w = 0; w < wWide; ++w) { *p[h][w] = i; printf("%d\n", *p[h][w]); i++; } } }}
动态创建一个二维数组
程序运行后只输出一个"1" 后 就弹出一个错误对话框..。
求解...
[解决办法]要用(*p[h])[w] = i这样的写法。
[解决办法]p后的[]优先级高于p前的*
是(*p)[][]
还是(*p[])[]
还是*p[][]
含义是不一样的
[解决办法]正如三楼所说,这是一个[]与*之间优先级的问题,应该是:
void Init(int*** p, int wWide, int wHigh)
{
int h = 0;
int w = 0;
int i = 1;
if (*p == NULL)
{
*p= (int**)malloc(wHigh * sizeof (int*));
for (h = 0; h < wHigh; ++h)
{
(*p)[h] = (int*)malloc(wWide * sizeof (int));
for (w = 0; w < wWide; ++w)
{
(*p)[h][w] = i;
printf("%d\n", (*p)[h][w]);
i++;
}
}
}
}
不过为了便于理解,不如写成:
void Init(int*** ptr, int wWide, int wHigh)
{
int h = 0;
int w = 0;
int i = 1;
int **p = *ptr;
if (p == NULL)
{
p= (int**)malloc(wHigh * sizeof (int*));
for (h = 0; h < wHigh; ++h)
{
p[h] = (int*)malloc(wWide * sizeof (int));
for (w = 0; w < wWide; ++w)
{
p[h][w] = i;
printf("%d\n", p[h][w]);
i++;
}
}
}
*ptr = p; /* 必不可少 */
}
这样更容易理解。
[解决办法]运算符的优先级
请这样用(*p[h])[w]