代码之家  ›  专栏  ›  技术社区  ›  lindelof

C中带有数组成员的结构

  •  5
  • lindelof  · 技术社区  · 14 年前

    最近,我回顾了一些C代码,发现了与以下内容等效的内容:

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

    double *some_pointer 相反呢?

    6 回复  |  直到 14 年前
        1
  •  8
  •   caf    14 年前

    如果你通过值“是”传递,它将复制所有内容。 但这就是指针存在的原因。

    //Just the address is passed 
    void doSomething(struct foo *myFoo)
    {
    
    }
    
        2
  •  3
  •   altendky    11 年前

    作为参数传递时,它将被复制,这是传递结构(尤其是大型结构)的非常低效的方法。但是,基本上,结构是通过指针传递给函数的。

    double some_big_array[VERY_LARGE_NUMBER];
    

    double *some_pointer
    

        3
  •  1
  •   nmichaels    14 年前

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

        4
  •  1
  •   pmg    14 年前

    sizeof (struct foo)

    您还可以看到“struct hack”(也通过指针传递):

    struct foo {
        int some_innocent_variables;
        double some_array[]; /* C99 flexible array member */
        /* double some_array[1]; ** the real C89 "struck 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 */
    
        5
  •  0
  •   Jim Brissom    14 年前

    是的,在C中,由于效率的原因,通常会传递一个指向结构的指针。

        6
  •  0
  •   Pablo A. Costesich    14 年前

    离题: 小心结构黑客,因为它是 not strictly standard compliant ;它忽略了自动填充。Unix IPC消息队列使用它(请参阅 struct msgbuf )但是,几乎可以肯定的是,它可以与任何编译器一起工作。