gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:44:31 25 4
gpt4 key购买 nike

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

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

是否保证以下两个片段的行为方式相同?

struct MyStruct s;
s.x = 0;
s.y = 0;
Foo(&s, 1);

对比

struct MyStruct s[1]; // stack-allocated array of size 1
s[0].x = 0;
s[0].y = 0;
Foo(s, 1);

最佳答案

答案是肯定的,它们实际上是一样的。首先,当在函数参数中使用时,数组作为指向其第一个元素的指针传递。实际上,在存储方面,C 中的所有对象都可以视为该类型的一个元素的数组。

关于c - 大小为 1 的数组与指向结构的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36928891/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com