0

使用指针处理二维数组是个好主意吗?

for( p = &a[0][0]; p < &a[N][N]; p++){
    *p = 0;
}

还是使用索引更好?

4

3 回答 3

4

您表示数组的方式并不能保证指针算术始终有效。鉴于您声明二维数组的方式,这可能不是问题,但它肯定不是好的风格。

然而,想象一下这个数组是动态分配的。像这样的东西:

int **p = malloc(ARR_SIZE * sizeof(*p));
for (i = 0; i < ARR_SIZE; i++) {
    p[i] = malloc(ARR_SIZE * sizeof(**p));
}

这是一个二维数组(排序),但不能保证分配的内存是连续的,因此会破坏你的循环。

于 2013-01-24T22:55:35.300 回答
2

You should alway use indexing, unless you are absolutely sure that you know what you are doing, and have some very good reason why you don't want to use indexing for array

It is much easier to understand and maintain. If someone else is looking at your code it will be easier for them, also it is more resistant to errors. Pointers are great thing, but lot of people use them in wrong way and abuse them, making programs difficult to understand, maintain and find and solve bugs in them. From my professional experience it is much better not to create "magic" with pointers unless you really have to and are absolutely sure that you know what you are doing.

于 2013-01-24T22:51:16.073 回答
0

不,这不是因为数据可能不会被同时存储(上面的代码假定行的第一个元素正好在前一行的最后一个元素之后开始)。

于 2013-01-24T22:56:13.457 回答