首页 > 解决方案 > 在 C 中的另一个函数中迭代数组

问题描述

在主函数中读取文件时,我填充了一个未知大小的数组。我想编写另一个函数来迭代这个数组,比较字符串并返回请求字符串的索引。

但是,我似乎无法遍历所有数组并仅获取第一个元素。

尝试打印在数组中找到的元素(来自findIndex)时,我收到以下错误:format specifies type 'char *' but the argument has type 'char'我需要更改为%cin printf,据我了解这是因为我正在迭代数组中的第一项,而不是整个数组。

这是因为我在主函数中创建了一个数组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; 
}

标签: arrayscsearchc-stringsfunction-definition

解决方案


您的函数的参数array类型不正确。

在这次呼吁中printf

printf("%s\n", array[i]);

参数array[i]具有类型char。因此,您不能将转换说明符s与类型的对象一起使用char

0 也是一个有效的索引。所以这个返回语句

return 0;

会混淆函数的调用者,因为它可能意味着找到了字符串,同时又没有找到字符串。

该函数可以通过以下方式声明和定义

int findIndex( char **array, int n, const char *item ) 
{
    int i = 0;

    while ( i < n && strcmp( array[i], item ) != 0 ) i++;

    return i;
}

尽管对于数组的索引和大小,最好使用无符号整数类型size_t而不是 type int

并且在 main 函数中可以这样调用

int pos = findIndex( items, index, some_string );

wheresome_string是应该在数组中搜索的字符串。

如果在数组中找不到字符串,pos则将等于数组的当前实际大小,index

因此,您可以在调用后例如在 main 中编写

if ( pos == index )
{
   puts( "The string is not present in the array." );
}

推荐阅读