[英]In c accessing first element of the struct using address of the struct and pointers
我注意到struct
地址和第一個元素地址看起來相同。 因此,我嘗試使用主struct
地址訪問struct
的第一個元素。 但是我遇到了錯誤。
在顯示的參數1的兼容類型中。
我在這里犯了什么錯誤?
碼
#include <stdio.h>
#include <stdlib.h>
#define BASE(class) *(&class)
struct animal {
int walk;
int hear;
};
struct bird {
struct animal *base;
int fly;
};
void display(struct animal *common) {
printf("All animal details hear=%d walk=%d ", common->hear, common->walk);
}
int main() {
struct bird peacockptr;
struct animal base;
base.hear = 1;
base.walk = 1;
peacockptr.base = &base;
struct bird *pecock = &peacockptr;
pecock->fly = 1;
printf("base address using peacock struct %d\n",
BASE(peacockptr)); // both are printing same address
printf("base address animal %d\n",
&base); // both are printing same address
display(&base); // here it work
display(BASE(peacockptr)); // getting error
}
確實,結構的地址與其第一個成員的地址相同。 但是,它們具有不同的類型 。 一個具有struct animal *
類型,另一個具有struct base *
類型。
在這種情況下,您可以在兩者之間進行轉換,但是您需要進行顯式轉換。
display((struct animal *)BASE(peacockptr));
另外,關於定義BASE
宏的方式:
#define BASE(class) *(&class)
*
和&
運算符互相抵消,因此實際上是一個空操作。 BASE(peacockptr)
等效於peacockptr
。
現在使用peacockptr
對您失敗的原因是,因為您已將peacockptr
定義為實例 , pecock
peacockptr
定義為指針 ,即您將命名與混淆。 切換名稱以反映用法:
struct bird peacock;
struct animal base;
base.hear=1;
base.walk=1;
peacock.base= &base;
struct bird *peacockptr =&peacock;
peacockptr->fly=1;
如前所述,當操作符取消指針時,可以刪除BASE
宏。
我清理並更正了您的代碼,並解釋了哪里出了問題:
#include <stdio.h>
#include <string.h>
struct animal
{
int walk;
int hear;
};
struct bird
{
struct animal *base;
int fly;
};
void display(struct animal *common)
{
printf("All animal details hear=%d walk=%d\n",common->hear, common->walk);
}
int main()
{
struct bird peacock; // removed ptr suffix, since it is not a pointer
struct animal base ;
base.hear=1;
base.walk=1;
peacock.base= &base;
struct bird *peacockptr = &peacock;
peacockptr->fly=1;
printf("base address using peacock struct %p\n", (void *)*(struct animal **)peacockptr); //This is the address of base using peackockptr
printf("base address animal %p\n", (void *)&base); //This is the address of base
display(&base);
display(*(struct animal **)peacockptr);
return 0;
}
請注意, peackock
的地址等於該結構的第一個元素的地址,該第一個元素是struct animal *
。 因此,您必須將peacockptr
為struct animal **
(因為它指向的是struct animal *
類型的第一個元素),然后對其進行取消引用以獲得base
的地址。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.