为什么不建议在 C 中使用指针进行数组访问

mam*_*man 5 c arrays pointers pointer-arithmetic

我正在学习 C 编程,我在网上看到了本教程,其中指出您应该始终尽可能多地使用 [] 运算符而不是指针算法。

https://www.cs.swarthmore.edu/~newhall/unixhelp/C_arrays.html#dynamic

你可以使用指针算术(但一般不要)

考虑下面的 C 代码

int    *p_array;
p_array = (int *)malloc(sizeof(int)*50);

for(i=0; i < 50; i++) {
  p_array[i] = 0;
}
Run Code Online (Sandbox Code Playgroud)

使用如下代码的指针算术有什么区别(为什么不推荐)

int    *p_array;
p_array = (int *)malloc(sizeof(int)*50);      // allocate 50 ints

int *dptr = p_array;

for(i=0; i < 50; i++) {
  *dptr = 0;
  dptr++;
}
Run Code Online (Sandbox Code Playgroud)

在哪些情况下使用指针算法会导致软件出现问题?这是不好的做法还是缺乏经验的工程师可能不注意?

len*_*nik 1

不推荐使用此代码:

int    *p_array;
p_array = (int *)malloc(sizeof(int)*50);      // allocate 50 ints

int *dptr = p_array;

for(i=0; i < 50; i++) {
  *dptr = 0;
  dptr++;
}
Run Code Online (Sandbox Code Playgroud)

因为 1) 无缘无故地有两个不同的指针指向同一个地方,2) 你不检查结果malloc()——众所周知,偶尔会返回 NULL,3) 代码不容易阅读,4) 它是很容易犯一个愚蠢的错误,以后很难发现。

总而言之,我建议使用这个:

int array[50] = { 0 };  // make sure it's zero-initialized
int* p_array = array;   // if you must =)
Run Code Online (Sandbox Code Playgroud)