问题描述
我有一个函数
struct Analysis reduce (int n, void* results)
其中n是要分析的文件数,我正在将一系列Analysis结构传递给结果。
Where n is the number of files to be analyzed, and I'm passing an array of Analysis structs to results.
分析结构定义如下:
struct Analysis {
int ascii[128]; //frequency of ascii characters in the file
int lineLength; //longest line in the file
int lineNum; //line number of longest line
char* filename;
}
我已经将空缺*这样,
struct Analysis resArray[n];
struct Analysis* ptr = results;
resArray[0] = ptr[0];
但我不知道如何正确遍历resArray。我已经尝试
but I can't figure out how to iterate through the resArray properly. I've tried
for (i = 0; i < n; i++){
printf("lineLength: %d\n", resArray[i].lineLength);
}
n = 3,而我得到的是垃圾值。 resArray [0]是正确的,但是resArray [1]是一个非常高的数字,而resArray [2]只是0。为什么resArray [1]或resArray [2]不能提供正确的值?如果我错误地增加了地址,那是有道理的,但是我只是在某个索引处访问数组。
with n = 3, and I'm getting garbage values. resArray[0] is correct, but resArray[1] is an insanely high number and resArray[2] is just 0. Why wouldn't resArray[1] or resArray[2] give the correct values? If I was incrementing the address incorrectly then it would make sense but I'm just accessing the array at a certain index. Pretty lost here!
推荐答案
您不能直接将指针分配给数组,因为它们是不同的类型因为array [n]是结构分析(*)[n]类型,而ptr是结构分析(*)类型
。在中查看更多信息。
You can't assign a pointer to an array directly because they are different typessince array[n] is type struct analysis(*)[n] and ptr is type struct analysis(*)
. Check here for more info.
这篇关于C-遍历通过void *的结构数组迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!