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

送分小仙女□ 提交于 2019-12-13 08:17:07

问题


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.

The Analysis struct is defined as follows:

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. 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. 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!


回答1:


resArray[0] is correct because there is "something":

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



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/39404854/c-iterating-over-an-array-of-structs-passed-through-a-void

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!