C 大小为1的数组与指向结构的指针

C 大小为1的数组与指向结构的指针,c,arrays,pointers,C,Arrays,Pointers,假设我有一个函数,它接受一个结构数组,定义如下: void Foo(struct MyStruct *s, int count) { for (int i = 0; i < count; ++i) { // Do something with s[i] } } vs 对。这两个选项都是堆栈分配的,只创建一个struct MyStruct的“实例”。您的编译器应该为这两个选项输出相同的机器代码。有关更多详细信息,请参见(C)和(C++)。答案是肯定的,它们实

假设我有一个函数,它接受一个结构数组,定义如下:

void Foo(struct MyStruct *s, int count) {
    for (int i = 0; i < count; ++i) {
        // Do something with s[i]
    }
}
vs


对。这两个选项都是堆栈分配的,只创建一个
struct MyStruct
的“实例”。您的编译器应该为这两个选项输出相同的机器代码。有关更多详细信息,请参见(C)和(C++)。答案是肯定的,它们实际上是相同的。首先,在函数参数中使用数组时,数组作为指向其第一个元素的指针传递。实际上,C中的所有对象在存储方面都可以被视为该类型元素的数组。

它们是相同的;证明-我编译并保存了MSVC 2015和GCC 4.9.3为这两个代码示例生成的汇编代码:

// Case 1: Pass by reference to single struct
typedef struct _mystruct
{
    int x;
    int y;
} mystruct;

void foo(mystruct *s, int count)
{
    int i;
    for(i = 0; i < count; i++)
    {
        (*(s + i)).x = 5; 
        (*(s + i)).y = 7;
    }
}

int main()
{
    mystruct ps;

    //mystruct as[1];


    foo(&ps, 1);
    //foo(as, 1);
    return 0;
}
在生成的程序集文件中,在GCC上它们完全相同,而在MSVC中,它们的唯一区别是:

  • 注释中的变量名(s vs as)
  • 引用的行号(因为每个版本中未注释不同的行号)

  • 因此,假设这两种方法是相同的,是安全的。

    OP询问C,链接是C++和java。它解释了如何在C++中如何进行堆栈分配以及它如何与java相关联——尽管C++和java之间进行了比较,但是它解释了堆栈分配是如何工作的。我刚刚添加了另一个链接,它也解释了纯C的堆栈分配。您可以看到它们生成了相同的机器代码
    struct MyStruct s[1]; // stack-allocated array of size 1
    s[0].x = 0;
    s[0].y = 0;
    Foo(s, 1);
    
    // Case 1: Pass by reference to single struct
    typedef struct _mystruct
    {
        int x;
        int y;
    } mystruct;
    
    void foo(mystruct *s, int count)
    {
        int i;
        for(i = 0; i < count; i++)
        {
            (*(s + i)).x = 5; 
            (*(s + i)).y = 7;
        }
    }
    
    int main()
    {
        mystruct ps;
    
        //mystruct as[1];
    
    
        foo(&ps, 1);
        //foo(as, 1);
        return 0;
    }
    
    // Case 2: 1-length array
    typedef struct _mystruct
    {
        int x;
        int y;
    } mystruct;
    
    void foo(mystruct *s, int count)
    {
        int i;
        for(i = 0; i < count; i++)
        {
            (*(s + i)).x = 5; 
            (*(s + i)).y = 7;
        }
    }
    
    int main()
    {
        //mystruct ps;
    
        mystruct as[1];
    
    
        //foo(&ps, 1);
        foo(as, 1);
        return 0;
    }