【发布时间】:2021-04-27 09:03:28
【问题描述】:
在主函数中读取文件时,我填充了一个未知大小的数组。我想写另一个函数来遍历这个数组,比较字符串并返回请求字符串的索引。
但是,我似乎无法遍历所有数组并仅获取第一个元素。
当尝试打印在数组中找到的元素(来自findIndex)时,我收到以下错误:format specifies type 'char *' but the argument has type 'char' 我需要在printf 中更改为%c,据我了解这是因为我正在迭代数组中的第一项,而不是整个数组。
这是因为我在主函数中创建了一个数组作为char *items[MAXKEY]?如何解决问题并从函数返回请求字符串的索引?
int findIndex(int index, char *array, char *item) {
for (int i = 0; i < index; i++) {
if (strcmp(&array[i], item) == 0) {
printf("%s\n", array[i]); // rising an error format specifies type 'char *' but the argument has type 'char'
// return i; // does not return anything
}
}
return 0;
}
int main () {
FILE *file;
char *items[MAXKEY];
char token[MAXKEY];
int index = 0;
// adding elements to the array
while (fscanf(file, "%s", &token[0]) != EOF) {
items[index] = malloc(strlen(token) + 1);
strcpy(items[index], token);
index++;
}
return 0;
}
【问题讨论】:
-
%s需要一个以 null 结尾的字符串 (char*),但array[i]是一个单个char。如果要打印单个字符,可以使用%c。 -
你在哪里以及如何打电话给
findIndex?
标签: arrays c search c-strings function-definition