比如说,有一个 proc.h 定义了一个数组,比如
proc.h:
struct proc
{
char p_stat;
char p_flags;
int p_pid;
} proc[100];
还有另外5个.c文件包括这个头文件。我没有看到任何此类 .c 文件为此数组分配内存。我认为是链接器为它分配内存。然而,出现在头文件中的应该只是一个声明。声明如何导致内存分配?我以为只有定义会导致内存分配。
谢谢,
最佳答案
Say, there is a proc.h which defines an array like
proc.h:
struct proc { char p_stat; char p_flags; int p_pid; } proc[100];
上面的代码实际上不仅定义了数据结构struct proc
,它还为包括文件头在内的每个文件声明/分配了一个数组。
一个广泛使用的习惯用法是使用 typedef 定义数据结构,如下所示:
typedef struct
{
char p_stat;
char p_flags;
int p_pid;
} proc_t;
或者只是在没有 typedef 的情况下简单地定义结构:
struct
{
char p_stat;
char p_flags;
int p_pid;
} proc_t;
然后在与 header 匹配的 c 文件中,您将实例化您的结构数组:
proc_t proc[100]; // if you've typedef'd the struct
struct proc_t proc[100]; // if you haven't typedef'd
然后在包括头文件在内的所有 C 文件中,要访问此全局结构,您将声明变量 extern。这样,所有 c 文件将共享对单个数据结构的访问权限。
我更喜欢在单个 header 中对结构进行类型定义,并通过仅通过函数调用(通过地址传递的对象)访问/操作该数据结构的实例来封装它,但这是个人品味和其他问题。
关于c - 如何为头文件中定义(声明?)的数组分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24681738/