gpt4 book ai didi

c - 指向 C 中结构的指针的工作示例

转载 作者:太空宇宙 更新时间:2023-11-04 07:56:48 24 4
gpt4 key购买 nike

我对 C 中的结构指针感到困惑,我的部分问题是我发现的示例似乎是错误的。

在此示例代码中,我找到了 here ,我仍然遇到可怕的错误:

warning: assignment from incompatible pointer type

#include <stdio.h>

struct Book
{
char name[10];
int price;
}

int main()
{
struct Book a; //Single structure variable
struct Book* ptr; //Pointer of Structure type
ptr = &a;

struct Book b[10]; //Array of structure variables
struct Book* p; //Pointer of Structure type
p = &b;

return 0;
}

有没有人有工作的例子供我学习?

最佳答案

改变:

p = &b;

进入:

p = b;

这是因为 b [已经] 是一个数组。因此,b 本身引用整个数组,结果指向第一个元素(即 &b[0])。您生成的是 Book ** 而不是 Book * [1]。

所以,这也可行:

p = &b[0];

更新:

[1] 我的错。这实际上生成了 struct Book (*)[10],它是一个指向固定大小(例如 10)的 Book 结构数组的指针,它与一个简单的 Book 指针。这会将数组长度添加为类型的一部分,因此指针/类型匹配更加严格/复杂。

struct Book (*)[10] 不匹配 [typewise] 到 struct Book * 并且匹配 < em>不同 长度固定数组大小指针(例如 struct Book (*)[20]),即使基类型(struct Book)相同。

但是,一旦定义,指针的取消引用/索引将是类似的。

此处的使用是无意的。这是一个有点高级的特性/技术,现在可以避免。我在实践中很少 [if ever] 遇到过它。

有关详细信息,请参阅:C pointers : pointing to an array of fixed size

关于c - 指向 C 中结构的指针的工作示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49497359/

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