gpt4 book ai didi

arrays - 在 C 中的另一个函数中迭代数组

转载 作者:行者123 更新时间:2023-12-04 08:13:05 24 4
gpt4 key购买 nike

在 main 函数中读取文件时,我填充了一个未知大小的数组。我想编写另一个函数来迭代这个数组,比较字符串并返回请求字符串的索引。
但是,我似乎无法遍历所有数组并仅获取第一个元素。
尝试打印在数组中找到的元素(来自 findIndex )时,出现以下错误:format specifies type 'char *' but the argument has type 'char'我需要更改为 %cprintf ,据我所知,这是因为我正在迭代数组中的第一项,而不是整个数组。
这是因为我在主函数中创建了一个数组 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而不是类型 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." );
}

关于arrays - 在 C 中的另一个函数中迭代数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65852902/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com