繁体   English   中英

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

[英]Passing dynamic array struct through function

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

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

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

我想在具有sscanf()的函数中使用main() 之外struct值 数组的初始化也被在主照顾 ()。

如何通过该函数传递 结构数组并设置它的一些结构值 唉,我讨厌指针

谢谢!

那将是:

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

这适合我

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

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

我想你也需要

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 

暂无
暂无

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

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