【发布时间】:2016-01-31 09:34:40
【问题描述】:
指针对很多事情都很有用,以至于有时无法理解它们在特定代码行中的含义。
例如,有时您使用指针来表示一系列元素:
char* char_array = "abcd";
int* int_array = malloc(5 * sizeof(*int_array));
有时您使用指针在堆上分配单个对象或使一个元素指向另一个元素:
int a = 5;
int* int_ptr = &a;
struct item* an_item = malloc(sizeof(*an_item));
当两者都使用碰撞时,连续的指针变得不可读:
struct cell** board;
// Does this represent a succession of cell allocated on the heap,
// a succession of pointers to uniques cells (like an array),
// a succession of pointers to multiples cells (like a two dimensional array)?
// Of course the more you add pointers the more it becomes confusing.
struct cell*** board;
我考虑过使用typedef 或宏来创建一个表示指针的类型,该指针用作引用或已被malloc 编辑过的东西。
这可能是双刃剑,因为在某些情况下我会获得可读性,但它也会混淆代码。
您有什么建议来编写更容易理解指针含义的代码?
【问题讨论】:
-
我真的不明白这个问题。如果您是初学者,指针可能会令人困惑,并且您建议的内容可能很有用,但是在习惯它之后,这没什么大不了的。指针总是以类似的模式使用,过一段时间你就会学会它们。
-
使用变量命名约定,以及描述其属性的指针声明上方的代码cmets(即,它是否将拥有它所指向的内容,以及它是否可能指向数组的第一个)
-
三重间接是令人困惑的,没有办法解决这个问题。尽量避免三重间接。
标签: c pointers pointer-to-pointer