简体   繁体   English

"如何调用和传递字符串数组并在函数内查找该数组的长度"

[英]How to call and pass array of string and find the length of that array inside the function

I am writing a program to check if a string is inside an array of strings.我正在编写一个程序来检查字符串是否在字符串数组中。 I predefined an array of words before the main method我在 main 方法之前预定义了一个单词数组

const char *items[] = {"a","b","c","d"};

then I have a function like然后我有一个像

bool isInside(const char *array[], char *s1){
 //which will try to compare all strings from the input array with s1
  int len = sizeof(array)/sizeof(array[0]);
  for (int i =0; i< len ; i++){
   //do string comparasion}
}

It worked before but not sure where I messed up the code now I got two errors and the function is only able to check the first string of the array with s1.它以前可以工作,但不确定我在哪里弄乱了代码,现在我遇到了两个错误,并且该函数只能使用 s1 检查数组的第一个字符串。

I found out the problem is that now len = 1 always.我发现问题是现在 len = 1 总是。

one of the errors is错误之一是

`warning: ‘sizeof’ on array function parameter ‘array’ will return size of ‘const char **’ [-Wsizeof-array-argument]` and the other one is 

isInside(items, words[i]))
      |                               ^~~~~~~~~
      |                               |
      |                               const char **
code.c:63:21: note: expected ‘char *’ but argument is of type ‘const char **’

How can I fix this or call this function so the length is correct and no type warning?如何解决此问题或调用此函数以使长度正确且没有类型警告?

Thanks a lot.非常感谢。

Arrays in C will degrade to pointers when passed as arguments to functions. C 中的数组在作为参数传递给函数时会降级为指针。 When they become pointers, their length cannot be retrieved by sizeof<\/code> .当它们成为指针时,它们的长度无法通过sizeof<\/code>检索。

You should pass the length of arrays as an additional argument to the function.您应该将数组的长度作为附加参数传递给函数。

Maybe your function can be modified as:也许您的功能可以修改为:

bool isInside(const char **array, int arrayLength, char *s1){
  for (int i =0; i< arrayLength; i++){
     const char* str = array[i];
     if(strcmp(str, s1) == 0){
        return 1;
     }
  }
  return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM