c - 如何区分不同指针的含义?

标签 c pointers pointer-to-pointer

指针有很多用途,有时无法理解它们在特定代码行中的含义。
例如,有时您使用指针来表示一系列元素:

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 的指针的指针。
这可能是双刃剑,因为在某些情况下我会获得可读性,但它也会混淆代码。
对于生成指针含义更易于理解的代码,您有何建议?

最佳答案

What do you recommend to produce code where the meaning of pointers is easier to understand?

的确,代码的外行人可能不清楚指针的含义。我建议在变量名称前加上前缀以赋予它们更多含义。

参见:https://en.wikipedia.org/wiki/Hungarian_notation#Examples

当然,您不必详细遵循此示例。您可以找到多种方式来添加前缀或组成您自己的方式。只要你在某个地方解释一下,你就应该做得很好。

关于c - 如何区分不同指针的含义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35112314/

相关文章:

c - Xeon Phi 上带有 GDB 的 LD_LIBRARY_PATH

pointers - Kotlin函数参数: Val cannot be reassigned

c - 如何将函数输出分配给数组类型?在 C 中?

c - 指向指针地址的指针

c - ‘struct file_operations’ 的强制函数

python - 有什么方法可以处理 Python 代码中的 C 扩展段错误?

c - 如何计算文本文件中相互重叠的单词

swift - 重叠访问指针

c - C 中使用指针到指针的链表实现

c - 指向数组的变量的地址与该变量本身的值之间的差异