通过函数传递动态数组结构

时间:2010-11-07 16:48:03

标签: c pointers dynamic struct

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

我有一个在main()中动态创建的结构数组,如下所示:

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

我希望在具有sscanf()的函数中使用main()之外的结构值。在main()上,数组的初始化也是小心

我如何通过该函数传递 结构数组并设置一些结构值呢?我讨厌指针

谢谢!

4 个答案:

答案 0 :(得分:5)

那将是:

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

答案 1 :(得分:3)

这对我有用

/* #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;
}

答案 2 :(得分:0)

C中的所有函数都是按值传递参数,因此您可以将指针传递给您想要修改的struct数组:

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

您可以使用以下方式调用此函数:

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

答案 3 :(得分:0)

我认为你需要

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

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