我需要将数组参数从main传递给函数,但是我无法弄清楚为什么它仅向下传递数组的第一个元素,而不是按预期传递整个数组。数组中的值来自argv。
有人可以指出我的错误吗?
#define MAXSTRING 1000;
int findMatches (const char *filename, char request[]) {
// iterating over request[] is giving individual characters of the first word, not all words.
// expected to have a full array of input words.
int len = strlen(request);
for (int i = 0; i < len; i++) {
printf("%s \n", request[i]);
}
}
int main (int agrc, char *argv[]) {
char *request[MAXSTRING];
int index = 0;
for (int i = 1; i < agrc; i++) {
request[index] = argv[i];
index++;
}
findMatches("filename.txt", request);
return 0;
}
char request[]
与相同char *request[MAXSTRING]
。前者声明一个字符数组(即一个字符串),后者声明一个指向char的指针数组,即一个字符串数组。
因此,请在您的函数中正确声明它:
int findMatches (const char *filename, char *request[]) {
接下来,您将需要一种方法来检测中包含的字符串数组的结尾request
。将计数传递给findMatches()
或将最后一个字符串安排为NULL。如果使用计数,则可以重新定义该函数以接受计数:
void findMatches (const char *filename, char *request[], int n) {
for (int i = 0; i < n; i++) {
printf("%s \n", request[i]);
}
}
并这样称呼它:
findMatches("filename.txt", request, agrc-1);
另外,MAXSTRING
in的使用char *request[MAXSTRING]
似乎很混乱。您似乎想要一个字符串数组,但MAXSTRING
似乎是一个字符串的最大长度。您的程序不太可能有1000个参数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句