c-中的指针“是指针;您是要使用'->'吗?”

时间:2018-11-21 12:23:06

标签: c pointers

我正在尝试使用指针将新值分配给嵌套结构中的afield, 但是我一直在标题中遇到编译错误, 这是我的代码:

    struct Territory{
int x1;
int x2;
int y1;
int y2;
};

struct Country{
   char *name;
   pCity *cities;
   int numCities;
   pTerritory *countryTerr;

};
typedef struct Territory* pTerritory;
typedef struct Country* pCountry;`struct Territory 
ter_for_country;
struct Country new_country;
pCountry country_pointer;
country_pointer = &new_country;

ter_for_country.x1 = 3;
ter_for_country.x2 = 3;
ter_for_country.y1 = 3;
ter_for_country.y2 = 3;

new_country.numCities=2;
new_country.countryTerr = &ter_for_country;

现在假设我想使用指针“ country_pointer”更改new_country的“ x1”,我该怎么做? 我试过了:

country_pointer->countryTerr->x1 = 25;

但是我遇到错误,您能帮忙吗? 谢谢

2 个答案:

答案 0 :(得分:0)

您的一级指针过多:pTerritory被定义为指向struct Territory的指针,而在struct Country中,您使countryTerr指向{{1 }}。这为您提供了一个指向指针的指针,您想要一个指向结构的指针。解决方案:将pTerritory更改为countryTerr类型(而不是pTerritory)。

答案 1 :(得分:0)

成员pTerritory *countryTerr实际上是类型struct Territory **(请注意,pTerritory已经是指针类型,您可以在*之后再添加一个*countryTerr

struct Country{
   char *name;
   pCity *cities;
   int numCities;
   pTerritory countryTerr;
};    

和您的声明country_pointer->countryTerr->x1 = 25应该可以按预期进行编译(和工作)。

无论如何,为了避免由于这样的“显式指针类型”而导致的陷阱,通常将*标记与普通类型一起理解,并且-在我看来-更直接,更容易阅读:

typedef struct Territory{
 int x1;
 int x2;
 int y1;
 int y2;
} Territory;

typedef struct Country{
   char *name;
   pCity *cities;
   int numCities;
   Territory *countryTerr;
} Country;