首页 > 解决方案 > 这个带有指向带有指针的结构的指针的c代码有什么问题?

问题描述

有人可以解释一下这段代码有什么问题吗?为什么我会收到编译错误?以及如何解决这个问题?

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);
                                                   ~~                      ^~~~~~~~~~~~~~~

标签: cpointersstruct

解决方案


您将结构定义为保存 (int *) 但在初始化结构时传入整数。那就是问题所在。这只是一个警告,所以编译器会让你知道你做了什么。它将 0 作为 (int *) 的值,这将在以后引起问题。


推荐阅读