【问题标题】:Iterate Over Array in Another Function in C在 C 中的另一个函数中迭代数组
【发布时间】: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


【解决方案1】:

你的代码有一些问题:

  • main() 中,您定义了一个大小为MAXKEYchar 数组,最多可容纳MAXKEY-1 个字符,但您还定义了一个具有相同大小的char 指针数组。字符串的个数和字符串的最大长度一样吗?
  • find_index() 的原型与您的目标不一致:您应该将字符串数组声明为char **arraychar *array[]
  • 返回0 失败也是一个问题,因为如果在索引0 找到字符串,这将是相同的值。失败返回 -1 似乎更合理。
  • file 没有打开,也没有关闭。
  • 您应该使用strdup() 而不是手动分配内存并复制字符串,尽管您正确地为空终止符分配了一个额外的字节。

这是修改后的版本:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int findIndex(char *array[], int count, const char *item) {
    for (int i = 0; i < count; i++) {
        if (strcmp(array[i], item) == 0) {
            return i;
        }
    }
    return -1;
}

#define MAXKEY 1000  // maximum number of keys

int main() {
    FILE *file; 
    char *items[MAXKEY];
    char token[100];
    int count;

    file = fopen("keys.txt", "r");
    if (file == NULL) {
        printf("cannot open keys.txt\n");
        return 1;
    }
    // adding elements to the array 
    for (count = 0; count < MAXKEY && fscanf(file, "%99s", token) == 1; count++) {
        items[count] = strdup(token);
        if (items[count] == NULL)
            break;
    }
    fclose(file);
    printf("Enter key: ");
    if (scanf("%99s", token) == 1) {
        int index = find_index(items, count, token);
        if (index < 0) {
            printf("Key %s not found\n", token);
        } else {
            printf("Key %s found at index %d\n", token, index);
        }
    }
    while (count --> 0) {
        free(items[count]);
    }
    return 0; 
}

【讨论】:

    【解决方案2】:

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

    在这次printf的电话中

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

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

    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 而不是类型int

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

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

    其中some_string 是应在数组中搜索的字符串。

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

    所以你可以在调用后例如在 main 中编写

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-07
      • 2017-10-11
      • 2015-04-18
      • 2015-03-15
      • 1970-01-01
      相关资源
      最近更新 更多