arrays - 在 C 中的另一个函数中迭代数组
问题描述
在主函数中读取文件时,我填充了一个未知大小的数组。我想编写另一个函数来迭代这个数组,比较字符串并返回请求字符串的索引。
但是,我似乎无法遍历所有数组并仅获取第一个元素。
尝试打印在数组中找到的元素(来自findIndex
)时,我收到以下错误:format specifies type 'char *' but the argument has type 'char'
我需要更改为%c
in 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;
}
解决方案
您的函数的参数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." );
}
推荐阅读
- microsoft-teams - 从自定义团队选项卡中的“文件”选项卡中确定所选项目
- python - 在 pyspark windows 方法中传递 orderby 列表的另一种方法
- angular - 如何使用 jasmine spy 为 window.location.pathname 编写单元测试?
- java - DB2 外部 java jar 文件存储过程错误
- spfx - 如何使用@pnp/sp查询SP列表中的person列获取姓名
- docker - 如何使用 kubernetes env 访问容器环境变量?
- excel - 日期不按年份分组的 Excel 数据透视表
- node.js - npm 脚本无法在 docker 容器的 workdir 中找到文件
- bash - 错误:“用户”指令仅在主进程以超级用户权限运行时才有意义
- c# - 如何在 Visual Studio 中启用自动填充选项