我被困在一些没有评分的作业上(这意味着练习).
我必须创建一个带有find_name
2个参数的函数.第一个参数是名称(字符串)的二维数组,第二个参数是用于在二维数组中查找名称的字符串,如果找到其他0,则函数必须返回1.
当我调用该函数(现在为空)时,我得到了这个 warning: passing argument 1 of 'find_name' from incompatible pointer type
这是重要的一点.
在主要
char strNameList[][2] = { { "Luca","Daniel"} ,{"Vivan","Desmond"},{"Abdul","Justin"}, {"Nina","Marlene"},{"Donny","Kathlene"} };
char strFindName[] = "\0";
printf("Please enter a name to look for: ");
gets(strFindName);
nSearch = find_name(strNameList, strFindName);
Run Code Online (Sandbox Code Playgroud)
功能
int find_name(char strNameList[][2], char strLookUp[])
Run Code Online (Sandbox Code Playgroud)
我是C的新手(我是学生),我对字符串(字符串数组等)感到困惑.
Who*_*aig 10
我假设你想要一个二维char指针数组.您在程序中的两个位置都声明strNameList不正确.你有:
char strNameList[][2] = { { "Luca","Daniel"} ,{"Vivan","Desmond"},{"Abdul","Justin"}, {"Nina","Marlene"},{"Donny","Kathlene"} };
Run Code Online (Sandbox Code Playgroud)
但是char[][N]
声明一个2D数组chars
,而不是char*
因此你被编译器警告你要为类型的项目分配一大堆指针值char
更改既您的声明(你的变量和你的函数参数):
const char *strNameList[][2]
Run Code Online (Sandbox Code Playgroud)
它声明了一个未知长度为2的数组的数组char*
,现在它与您的初始化列表相匹配.此外,const
还添加了因为(a)我假设您不打算在函数中修改该名称列表,并且(b)分配给char*
via初始化程序的可写字符串文字声明在C中是未定义的行为,并且在C++中正式弃用,所以你不应该使用它.同样,您的lookup-name也可能没有被修改,所以也声明它const
.
结果:
const char * strNameList[][2] = {
{"Luca","Daniel"} ,
{"Vivan","Desmond"},
{"Abdul","Justin"},
{"Nina","Marlene"},
{"Donny","Kathlene"}
};
Run Code Online (Sandbox Code Playgroud)
在你的功能:
int find_name(const char * strNameList[][2], const char strLookUp[])
Run Code Online (Sandbox Code Playgroud)
最后但同样重要的是,除非你有一个水晶球,否则你的find_name()
功能无法通过给定的信息知道传递的名单中有多少名字.我宁愿你现在看到这一点,而不是想知道后来发生了什么.您需要(a)使用find_name()
知道的令牌值终止列表,或者(b)将列表中的名称数传递给find_name()
.对于他们自己,但我更喜欢后者:
int find_name(const char * strNameList[][2], size_t nNameListSize, const char strLookUp[])
Run Code Online (Sandbox Code Playgroud)
并通过以下方式在呼叫者方面调用它:
find_name(strNameList, sizeof(strNameList)/sizeof(strNameList[0]), strFindName)
Run Code Online (Sandbox Code Playgroud)
这样做:
#define STOPPER_NAMELIST NULL
char * strNameList[][2] = {
{ "Luca","Daniel"},
{"Vivan","Desmond"},
{"Abdul","Justin"},
{"Nina","Marlene"},
{"Donny","Kathlene"}
{STOPPER_NAMELIST, STOPPER_NAMELIST}
};
size_t sizeNameList(const char * strNameList[][2])
{
size_t size = 0;
while ((strNameList[size][0] != STOPPER_NAMELIST) &&
(strNameList[size][0] != STOPPER_NAMELIST))
++ size;
return size;
}
int find_name(char * strNameList[][2], char strLookUp[])
{
size_t size = sizeNameList(strNameList);
...
}
...
nSearch = find_name(strNameList, strFindName);
Run Code Online (Sandbox Code Playgroud)
此方法使用带有条目[]
的char *
数组的open array()2
.
更新:
您可以在带有名称的阵列中添加一个塞子元素,然后不需要随阵列本身一起传递阵列的大小,因为大小总是可以通过扫描阵列成员直到找到塞子来确定.