C语言向函数传递二维数组出现Conflicting Types报错问题咨询
问题原因
- C语言要求函数必须先声明或定义,才能被调用。你的代码中
testFunction的定义放在main函数之后,main中调用该函数时编译器还未读取到它的定义,会默认按照返回值为int的隐式规则处理,后续读到返回值为bool的函数定义时,就会触发类型冲突报错。 - 你传递二维数组的参数写法本身完全正确,不需要额外转换为指针。
解决方案
有两种常见修复方案,均可保留直接传递二维数组的写法:
方案1:在main函数前添加函数声明
在头文件引入之后、main函数定义之前,补充函数声明即可:
bool testFunction(char array[][6], int i, int j);
完整修改示例:
#include <stdio.h> #include <stdbool.h> // 补充函数声明 bool testFunction(char array[][6], int i, int j); int main() { char array[6][6] = { {'.', '.', '.', '.', '.', '.'}, {'.', '.', '.','.', '.', '.'}, {'.', '.', '.', '.', '.', '.'}, {'.', '.', '.', '.', '.', '.'}, {'.', '.', '.', '.', '.', '.'}, {'.', '.', '.', '.', '.', '.'} }; bool success = testFunction(array, 0, 1); return 0; } bool testFunction(char array[][6], int i, int j){ return true; }
方案2:调整函数定义顺序
直接把testFunction的完整定义挪到main函数之前,让编译器先读取到函数定义再处理调用:
#include <stdio.h> #include <stdbool.h> bool testFunction(char array[][6], int i, int j){ return true; } int main() { char array[6][6] = { {'.', '.', '.', '.', '.', '.'}, {'.', '.', '.','.', '.', '.'}, {'.', '.', '.', '.', '.', '.'}, {'.', '.', '.', '.', '.', '.'}, {'.', '.', '.', '.', '.', '.'}, {'.', '.', '.', '.', '.', '.'} }; bool success = testFunction(array, 0, 1); return 0; }
内容的提问来源于stack exchange,提问作者africanxmamba
相关产品推荐
相关产品推荐

