[英]What is wrong with this c code with a pointer to struct with pointer?
有人可以解釋一下這段代碼有什么問題嗎? 為什么我收到編譯錯誤? 以及如何解決這個問題?
struct recPtr_t{
int * l;
int * w;
};
typedef struct recPtr_t recPtr;
recPtr r1 = {0,0};
recPtr * rPtr1 = &r1;
printf("Default dimensions of rectangle are %d and %d\n", rPtr1->l, rPtr1->w);
警告:
rectangle.c:28:59: warning: format specifies type 'int' but the argument has type 'int *' [-Wformat]
printf("Default dimensions of rectangle are %d and %d\n", (int *)rPtr1->l, (int *)rPtr1->w);
~~ ^~~~~~~~~~~~~~~
rectangle.c:28:76: warning: format specifies type 'int' but the argument has type 'int *' [-Wformat]
printf("Default dimensions of rectangle are %d and %d\n", (int *)rPtr1->l, (int *)rPtr1->w);
~~ ^~~~~~~~~~~~~~~
您定義結構以保存 (int *) 但在初始化結構時您傳入整數。 那就是問題所在。 這只是一個警告,所以編譯器會讓你知道你做了什么。 將 0 作為 (int *) 的值,這將在以后引起問題。
您應該將結構更改為包含整數而不是整數指針。
你應該有:
struct recPtr_t{
int l;
int w;
};
這將解決您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.