比如了定义如下函数和字符串的二维数组,如何定义一个函数,把二维数组当做形参传递进去?
1 #include<cstring> 2 #include<iostream> 3 #include<stdio.h> 4 #include<stdlib.h> 5 6 using namespace std; 7 8 void threeArr(char* arr[][5]); 9 10 int main(){ 11 char *arrays[][5] = {{"bcda","thbcda","weccgh","uk3e","13bjf"}, 12 {"gjh","df7h","5i6sf","yhjj5","xkh"}, 13 {"nml","lwfm","fbjyn"}}; 14 cout<<arrays[0][4]<<endl; 15 threeArr(arrays); 16 return 0; 17 }
这个程序编译通不过,提示错误信息如下,一直没有弄懂该如何定义函数的形式和传递参数,谢谢大家能够提供帮助。
1 ||=== Build file: "no target" in "no project" (compiler: unknown) ===| 2 ||In function 'int main()':| 3 |13|warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]| 4 || undefined reference to `threeArr(char* (*) [5])'| 5 ||error: ld returned 1 exit status| 6 ||=== Build failed: 2 error(s), 13 warning(s) (0 minute(s), 2 second(s)) ===|
人家不是告诉你了..二维数组是行列固定的.
你第一行和第二行是一样的.但第三行为什么就少了..
不是这个问题,改成下面样子,也是一样的错误,个人认为主要是函数定义和传递形参方式的问题,只是不知道怎么去改。
char *arrays[3][5] = {{"bcda","thbcda","weccgh","uk3e","13bjf"}, {"gjh","df7h","5i6sf","yhjj5","xkh"}, {"nml","lwfm","fbjyn","huxue","qibo"}};
@疯子也疯狂: 你定义个函数看看.你这函数连函数体都没.下面的异常
undefined reference to `threeArr(char* (*) [5])'|
@吴瑞祥: 主要是怎么定义函数和函数参数形式的问题,函数体可以为空,这个没有什么影响。定义成
void threeArr(char* arr[][5]){}
一样的错误.
@疯子也疯狂: void threeArr(char arr[3][5]){}呢?
@吴瑞祥: 如果定义成void threeArr(char arr[3][5]){}的形式,那么arr[3][5]中的每一个元素就只能是单个的char类型了,而我想每个元素类型为字符串类型,也就是char *的形式,但是这样传递参数就会报错。
你想用交错数组,进行传参是把
谢谢,交错数组学习了。我使用下面的形式,实现了同样的功能,目前遇到的问题则是:
1、为什么定义成char** test[] = {test0,test1,test2};就可以,而直接初始化为第6行的形式就不行呢?
2、如何确定数组元素的个数呢?比如:char** test[] = {test0,test1,test2};中确定test有3个元素。
以及确定test0中有5个元素。
1 char* test0[] = {"bcda","thbcda","wec3gh02","uk3e","13bjf"}; 2 char* test1[] = {"gjh","df7h","5i6sf","yhjj5","xkhchar14"}; 3 char* test2[] = {"nml","lwfm","fbjyn","huxue","qibo"}; 4 char** test[] = {test0,test1,test2}; 5 /* 6 char** test[3] = {{"bcda","thbcda","wec3gh02","uk3e","13bjf"}, 7 {"gjh","df7h","5i6sf","yhjj5","xkhchar14"}, 8 {"nml","lwfm","fbjyn","huxue","qibo"} 9 }; 10 */ 11 12 cout<<test[0][2]<<endl; 13 cout<<test[0][2][3]<<endl; 14 test[0][2] = "test302"; 15 cout<<test[0][2]<<endl; 16 cout<<test[0][2][3]<<endl; 17 cout<<*(test0+2)<<endl;
传参是对的,唯一的问题是函数只有声明没有定义。可能与你的编译器有关,换vs试试