如下所示,我希望将一个由char **x
定义的变量作为只读传递给一个函数.
一本参考书显示了线性搜索源代码,它通过将变量作为由const int a[]
定义的临时参数传递给search
函数来对由char *x
定义的变量执行线性搜索.
所以我突然想到了一个 idea ,如果是弦呢?然后我编写了下面的代码.
GCC、叮当和MSVC的分析可以找到here个.
// Linear Search
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int scanf_s(const char *format ,...); // for gcc and clang environment
// int search(const char **a, int n, char *key) { //※[1]not allowed in c lang specification⇒NG
// int search(char * const *a, int n, char *key) { //※[2]⇒NG
// int search(const char * const *a, int n, char *key) { //※[3]warning occured in gcc and clang!!
// int search(char const * const *a, int n, char *key) {//※[4]same as above
// int search(const char * const a[], int n, char *key) {//※[5]same as above
// int search(const char *a[], int n, char *key) { //※[6]I thought this was ok, but warning occured in gcc and clang!!
int search(char **a, int n, char *key) { //in conclusion, gcc,clang and MSVC only allowing this!!
int i = 0;
for (i = 0; i < n; i++) {
if (strcmp(a[i], key) == 0)
return i;
}
return -1;
/* or while style!! the reference book shows this style!!
while (1) {
if (i == n)
return -1;
if (strcmp(a[i], key) == 0)
return i;
i++;
}
*/
}
int main(void) {
char **x;
char *ky;
int nx;
int idx;
int i;
puts("Linear Search");
printf("How many Elements??:");
scanf_s("%d", &nx);
x = malloc(sizeof(char*) * nx);
if (x == NULL) {
printf("Pointer to Pointer x malloc failed!!\n");
exit(EXIT_FAILURE);
}
for (i = 0; i < nx; i++) {
printf("x[%d]:", i);
x[i] = malloc(sizeof(char) * 35);
if (x[i] == NULL) {
printf("Pointer Array x[] malloc failed!!\n", i);
exit(EXIT_FAILURE);
}
scanf_s("%s", x[i], 35);
}
printf("Target Value:");
ky = malloc(sizeof(char) * 35);
if (x == NULL) {
printf("target value malloc failed!!\n");
exit(EXIT_FAILURE);
}
// Or
// ky = calloc(35, sizeof(char));
scanf_s("%s", ky, 35);
idx = search(x, nx, ky);
if (idx == -1)
puts("no target value.");
else
printf("%s is in x[%d]!!\n", ky, idx);
free(ky);
for (i = 0; i < nx; i++) {
free(x[i]);
}
free(x);
system("pause");
return 0;
}
代码为const
的代码会使GCC和Clang显示警告,尽管msvc可以在没有任何警告的情况下进行编译,如注释(※[1]~[6])所示.
那么,如何在search
函数必须接受由char **x
定义的变量作为只读参数的情况下编写代码呢?