简体   繁体   English

C-遍历通过void *的结构数组迭代

[英]C- Iterating over an array of structs passed through a void*

I have a function 我有一个功能

struct Analysis reduce (int n, void* results)

Where n is the number of files to be analyzed, and I'm passing an array of Analysis structs to results. 其中n是要分析的文件数,我将一个Analysis结构数组传递给结果。

The Analysis struct is defined as follows: Analysis结构定义如下:

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;
}

I've cast the void * as such, 我已经将空白*

struct Analysis resArray[n];
struct Analysis* ptr = results;
resArray[0] = ptr[0];

but I can't figure out how to iterate through the resArray properly. 但我不知道如何正确地遍历resArray。 I've tried 我试过了

for (i = 0; i < n; i++){
  printf("lineLength: %d\n", resArray[i].lineLength);
}

with n = 3, and I'm getting garbage values. n = 3,而我得到的是垃圾值。 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? resArray [0]是正确的,但是resArray [1]是一个非常高的数字,而resArray [2]只是0。为什么resArray [1]或resArray [2]不能提供正确的值? 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! 这里真丢人!

resArray[0] is correct because there is "something": resArray [0]是正确的,因为存在“某物”:

resArray[0] = ptr[0];

Other elements are garbage because you didn't set there any values. 其他元素是垃圾,因为您没有在其中设置任何值。 If you want to copy entire array you need to change copying method to: 如果要复制整个阵列,则需要将复制方法更改为:

for (i = 0; i < n; i++)
{
  resArray[i] = ptr[i];
}

You can't assign a pointer to an array directly because they are different types since array[n] is type struct analysis(*)[n] and ptr is type struct analysis(*) . 您不能直接将指针分配给数组,因为它们是不同的类型, since array[n] is type struct analysis(*)[n] and ptr is type struct analysis(*) Check here for more info. 在这里查看更多信息。

Hopefully this code will help you. 希望这段代码对您有所帮助。

#include <stdio.h>
#define d 3
struct Analysis {
    int ascii[128];
    int lineLength;
    int lineNum;
    char *filename;
};

struct Analysis Analyses[d];

struct Analysis reduce(int n, void *results) {

    struct Analysis resArray[n];
    struct Analysis *ptr = results;

    for (int i = 0; i < n; i++) {
        resArray[i] = ptr[i];
    }

    for (int i = 0; i < n; i++) {
        printf("lineLength: %d\n", ptr[i].lineLength);
    }

    return *ptr;
}

int main(void) {
    struct Analysis a = {{5}, 2, 2, "George"};
    struct Analysis b = {{6}, 3, 3, "Peter"};
    struct Analysis c = {{7}, 4, 4, "Jane"};
    Analyses[0] = a;
    Analyses[1] = b;
    Analyses[2] = c;
    reduce(d, &Analyses);
    return 0;
}

You can try it online . 您可以在线尝试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM