简体   繁体   中英

Passing dynamic array struct through function

struct aPoint {
        int somaVertical;
        int somaHorizontal;
        int valor;
};

I have an array of structs dynamically created in main(), like so:

struct aPoint *ps = malloc( sizeof(struct aPoint) * columns * rows )

And I want to work with its struct values outside of main() in a function that has sscanf() . The initialization of the array is also taken care of on the main().

How can I pass the array of structs through that function and set some struct values of it aswell? Argh I hate pointering !

Thanks!

That would be:

    int readStuff(struct aPoint *ps, size_t len, const char *someVar)
    {
        unsigned int i;
        for (i = 0; i < len; i++) {
           sscanf(someVar, "%d", &(ps[i].somaVertical));
           /* And so on for the other fields */
        }
        /* Return whatever you're returning here */
    }

    const size_t len = colunas * linhas;
    struct aPoint *ps = calloc(len, sizeof(struct aPoint));
    int success = readStuff(ps, len, arrayOfNumbers);

This works for me

/* #include <assert.h> */
#include <stdio.h>
#include <stdlib.h>

struct aPoint {
  int somaVertical;
  int somaHorizontal;
  int valor;
};

int readStuff(struct aPoint *data, int rows, int cols) {
  sscanf("42", "%d", &data[3].somaVertical);
  sscanf("142", "%d", &data[3].somaHorizontal);
  sscanf("-42", "%d", &data[3].valor);
  return 0;
}

int main(void) {
  struct aPoint *ps;
  int colunas, linhas;

  colunas = 80;
  linhas = 25;
  ps = malloc(sizeof *ps * colunas * linhas);
  /* assert(ps); */ /* thanks Tim */
  if (ps) {
    readStuff(ps, linhas, colunas);
    printf("%d %d %d\n", ps[3].somaVertical, ps[3].somaHorizontal, ps[3].valor);
    free(ps);
  } else {
    fprintf(stderr, "no memory.\n");
    exit(EXIT_FAILURE);
  }
  return 0;
}

All functions in C are passed arguments by value, so you can pass a pointer to the struct array you wish to modify:

int readStuff(struct aPoint *p, int numStruct)
{
   ...
   for(i=0; i<numStruct; i++)
   {
      sscanf(someVar, "%d", &(*(p+i).valor) );
   }
   ...
}

You can call this function with:

struct aPoint *ps = malloc( sizeof(struct aPoint) * columns * rows );
...
readStuff(ps, columns * rows);

I think you need either

readStuff(ps); 
...
sscanf(someVar, "%d", &(ps[index].valor)); // using index in readStuff

or

readStuff(ps + index); // using index in main
...
sscanf(someVar, "%d", &(ps->valor)); // or &ps[0].valor, that's equivalent 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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