编译报错:invalid use of undefined type ‘struct Square’ 问题求助
编译报错:invalid use of undefined type ‘struct Square’ 问题求助
嗨,我来帮你排查这个编译错误的问题~
你遇到的这个报错,核心原因是编译器在处理Box结构体定义的时候,找不到struct Square的定义。仔细看你的代码就能发现问题所在:
你先定义了struct box,里面写了struct Square ** squares;,但你后面实际定义的结构体是struct square(注意这里是小写的s),然后通过typedef把它命名为Square。C语言里结构体的标签是严格区分大小写的,struct Square和struct square会被编译器当成两个完全不同的类型,自然就会报错说struct Square未定义了。另外你的Box结构体里的struct Box * next;也有同样的问题——你定义的结构体标签是box,不是Box。
给你两个可行的修复方案:
方案一:用前向声明+调整定义顺序
因为Square和Box是互相引用的(Square里有Box*,Box里有Square**),所以先做前向声明,再定义结构体和typedef,这样编译器就能提前知道这两个类型的存在了:
// 先前向声明两个结构体 struct square; struct box; // 提前typedef,后续可以直接用别名 typedef struct square Square; typedef struct box Box; // 定义Box结构体,现在可以直接用Square** struct box { Square ** squares; /* array of Squares */ int numbers; int possible[9]; int solvable; Box * next; }; // 定义Square结构体 struct square { int number; int possible[9]; /* the array is only made of 0 and 1 each index corresponds to a number: ex: index 4 == number 5 ... 1 tells me that 5 cannot go into this scare 0 tells me that 5 can go into this scare */ int solvable; /* will be subtracted 1 each time and when it is 1 it's because is solvable */ Box * box; /* tells me the corresponding box */ int row; int column; };
方案二:修正结构体标签的大小写
如果你不想调整代码顺序,也可以直接把Box结构体里的标签改成和后面定义一致的小写形式:
typedef struct box { struct square ** squares; /* 把struct Square改成struct square */ int numbers; int possible[9]; int solvable; struct box * next; /* 把struct Box改成struct box */ } Box; /* square is a single number in the board */ typedef struct square { int number; int possible[9]; /* the array is only made of 0 and 1 each index corresponds to a number: ex: index 4 == number 5 ... 1 tells me that 5 cannot go into this scare 0 tells me that 5 can go into this scare */ int solvable; /* will be subtracted 1 each time and when it is 1 it's because is solvable */ Box * box; /* tells me the corresponding box */ int row; int column; } Square;
至于你跟着的YouTube教程里没出现这个错误,大概率是教程里的代码做了正确的前向声明或者标签大小写一致,可能你在抄代码的时候没注意到这些细节~
备注:内容来源于stack exchange,提问作者Eduardo Fernandes
相关产品推荐
相关产品推荐

