结构与C中的数组成员

时间:2010-09-13 20:43:29

标签: c arrays struct

最近我查看了一些C代码,发现了与以下内容相同的内容:

struct foo {
    int some_innocent_variables;
    double some_big_array[VERY_LARGE_NUMBER];
}

几乎完全是C中的一个新手,但几乎完全是新手,我是否正确地认为这个结构因使用数组成员而在使用空间方面效率极低?将此结构作为参数传递给函数时会发生什么?它是否完整地复制到堆栈中,包括完整的数组?

在大多数情况下,改为double *some_pointer会更好吗?

6 个答案:

答案 0 :(得分:7)

如果你通过值是,它会复制一切。 但这就是指针存在的原因。

//Just the address is passed 
void doSomething(struct foo *myFoo)
{

}

答案 1 :(得分:2)

作为参数传递它将被复制,这是传递结构的非常低效的方式,特别是大结构。但是,基本上,结构通过指针传递给函数。

之间进行选择
double some_big_array[VERY_LARGE_NUMBER];

double *some_pointer

仅取决于程序设计以及如何使用此字段/结构。后者允许使用可变大小的存储,但是可能需要动态分配。

答案 2 :(得分:1)

正如其他人所说,这种类型的对象通常会传递指针(总是sizeof (struct foo)个字节,通常是4个字节)。

您可能还会看到“struct hack”(也传递了指针):

struct foo {
    int some_innocent_variables;
    double some_array[]; /* C99 flexible array member */
    /* double some_array[1]; ** the real C89 "struck hack" */
}

这个“struct hack”获得了malloc调用大小的数组。

/* allocate an object of struct foo type with an array with 42 elements */
struct foo *myfoo = malloc(sizeof *myfoo + 42 * sizeof *myfoo->some_array);
/* some memory may be wasted when using C89 and
   the "struct hack" and this allocation method */

答案 3 :(得分:0)

是的,在C中,由于效率原因,你通常会将指针传递给周围的结构。

答案 4 :(得分:0)

在结构中使用数组有很多理由。其中之一是结构通过值传递给函数,而数组通过引用传递。也就是说,这个结构可能会传递给带指针的函数。

答案 5 :(得分:0)

编辑:只要您通过引用传递它(使用指针),该结构就可以了。

Offtopic: 谨防结构hack,因为它是not strictly standard compliant;它忽略了自动填充。但是,Unix IPC消息队列使用它(参见struct msgbuf),几乎可以肯定它可以与任何编译器一起使用。

也就是说,使用该结构的函数可能会使用指针而不是使用副本。