在下面的代码中,我得到了作为注释提及的警告。 请帮助我解决这些警告。
//**expected ‘char **’ but argument is of type ‘char *’**
void inputArray(char ** arr, int size, char toSearch[]);
int search(char ** arr, int size, char * toSearch);
int main() {
char *array[5] = {0}; //to check if array is empty later
int size = 5, searchIndex;
char toSearch[] = "hello";
array[0] = "hello";
// **passing argument 1 of ‘search’ from incompatible pointer type [-Wincompatible-pointer-types]**
searchIndex = search(array, size, toSearch);
if (searchIndex == -1) {
printf("%s does not exists in array.", toSearch);
//**passing argument 1 of ‘inputArray’ from incompatible pointer type [-Wincompatible-pointer-types]**
inputArray(array, size, toSearch);
} else
printf("%s is found at %d position.", toSearch, searchIndex + 1);
return 0;
}
/*search string*/
int search(char ** arr, int size, char toSearch[]) {
int index = 0;
// Pointer to last array element arr[size - 1]
// **warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]**
int * arrEnd = (arr + size - 1);
/*
* Run a loop from start of array to last array element (arr <= arrEnd),
* until current array element does not match element to search.
*/
//**warning: comparison of distinct pointer types lacks a cast**
while (arr <= arrEnd && *arr != toSearch) {
printf("not equal: %d \n", index);
arr++;
index++;
}
//**warning: comparison of distinct pointer types lacks a cast**
if (arr <= arrEnd)
return index;
return -1;
}
//adding a string if not found in search
void inputArray(char ** arr, int size, char toSearch[]) {
int i;
for (i = 0; i < size; i++) {
if (arr[i] == 0) //stores string where ever an empty place is found.
{
arr[i] = toSearch;
printf("added: %s", arr[i]);
break;
}
}
}
答案 0 :(得分:1)
在函数search
中,arrEnd
的初始化类型与arr
的类型相同:指针上的+
和-
运算符不会更改类型,只有&
,*
(带前缀)和强制类型转换可以更改指针类型的表达式。因此,只需替换:
int * arrEnd = (arr + size - 1);
使用
char ** arrEnd = (arr + size - 1);
您提供的代码(与gcc一起编译)没有其他警告。