|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
代码1:
- #include <stdio.h>
- #include <stdlib.h>
- #define Node_num 1
- #define STR '&'
- struct Node {
- char str;
- int x, y;
- };
- void init(struct Node **node, int num);
- int main(void) {
- struct Node node[Node_num];
- // node : struct Node node*
- init(&node, Node_num);
- printf("Ok\n");
- return 0;
- }
- void init(struct Node **node, int num) {
- for (int i = 0; i < num; i++) {
- (*(node) + i)->str = STR;
- }
- };
复制代码
报错:
- $ gcc game_1.c &&./a.out
- game_1.c: 在函数‘main’中:
- game_1.c:18:8: 错误:传递‘init’的第 1 个参数时在不兼容的指针类型间转换 [-Wincompatible-pointer-types]
- 18 | init(&node, Node_num);
- | ^~~~~
- | |
- | struct Node (*)[1]
- game_1.c:12:25: 附注:需要类型‘struct Node **’,但实参的类型为‘struct Node (*)[1]’
- 12 | void init(struct Node **node, int num);
- | ~~~~~~~~~~~~~~^~~~
复制代码
代码2:
- #include <stdio.h>
- #include <stdlib.h>
- #define Node_num 1
- #define STR '&'
- struct Node {
- char str;
- int x, y;
- };
- void init(struct Node *node, int num);
- int main(void) {
- struct Node node[Node_num];
- // node : struct Node node*
- init(node, Node_num);
- printf("Ok\n");
- return 0;
- }
- void init(struct Node *node, int num) {
- for (int i = 0; i < num; i++) {
- (*(node + i)).str = STR;
- }
- };
复制代码
通过:
- $ gcc game_1.c &&./a.out
- Ok
复制代码
为什么?
- struct Node node[Node_num];
- init(&node, Node_num);
复制代码
我们首先分析,对数组取地址,得到的是什么?
C语言标准规定, 当数组名作为数组定义的标识符(也就是定义或声明数组时)、sizeof 或 & 的操作数时,它才 表示整个数组本身,在其他的表达式中,数组名会被转换为指向第 0 个元素的指针(地址)。
也就是,&node得到的是数组的地址。
因此在编译器编译时,会出现类似错误:
error C2664: 'init' : cannot convert parameter 1 from 'struct Node (*)[1]' to 'struct Node ** '
你想得到的是数组内的一个具体元素的指针,然后以指针的形式,取进行赋值。
所以,先考虑如何得到这个数组元素的指针:
struct Node node[Node_num];
node即为第一个元素的指针。
所以,第一种方法:
- #include <stdio.h>
- #include <stdlib.h>
- #define Node_num 1
- #define STR '&'
- struct Node {
- char str;
- int x, y;
- };
- void init(struct Node *node, int num);
- int main(void) {
- struct Node node[Node_num];
- // node : struct Node node*
- init(node, Node_num);
- printf("Ok\n");
- return 0;
- }
- void init(struct Node *node, int num) {
- for (int i = 0; i < num; i++) {
- ((node) + i)->str = STR;
- }
- };
复制代码
如果非要用原帖子内的这模式来完成,那么可以改成
- #include <stdio.h>
- #include <stdlib.h>
- #define Node_num 1
- #define STR '&'
- struct Node {
- char str;
- int x, y;
- };
- void init(struct Node **node, int num);
- int main(void) {
- struct Node node[Node_num];
- // node : struct Node node*
- struct Node *p= &node[0];
- init(&p, Node_num);
- return 0;
- }
- void init(struct Node **node, int num) {
- for (int i = 0; i < num; i++) {
- (*(node) + i)->str = STR;
- }
- };
复制代码
|
|