hanss
hanss

Reputation: 21

How to set the size of this array c++

I got c++ code, generated from the matlab coder, but I'm not sure, how to set the size of the array correct.

static emxArray_real_T *argInit_d7351x5_real_T()
{
  emxArray_real_T *result;
  static int iv0[2] = { 2, 5 };                                                  

  int idx0;
  int idx1;

  // Set the size of the array.
  // Change this size to the value that the application requires.
  result = emxCreateND_real_T(2, *(int (*)[2])&iv0[0]);

  // Loop over the array to initialize each element.
  for (idx0 = 0; idx0 < result->size[0UL]; idx0++) {
    for (idx1 = 0; idx1 < 5; idx1++) {
      // Set the value of the array element.
      // Change this value to the value that the application requires.
      result->data[idx0 + result->size[0] * idx1] = argInit_real_T();
    }
  }

  return result;
}

//
// Arguments    : void
// Return Type  : double
//
static double argInit_real_T()
{
  return 1.0;
}

I need a 10x5 Matrix filled the data from the argInit_real_T function, is it right, to change iv0[0] to 10?? How does the int (*)[2] command work?

struct emxArray_real_T
{
  double *data;
  int *size;
  int allocatedSize;
  int numDimensions;
  boolean_T canFreeData;
};

emxArray_real_T *emxCreateND_real_T(int numDimensions, int *size)
{
  emxArray_real_T *emx;
  int numEl;
  int i;
  emxInit_real_T(&emx, numDimensions);
  numEl = 1;
  for (i = 0; i < numDimensions; i++) {
    numEl *= size[i];
    emx->size[i] = size[i];
  }

  emx->data = (double *)calloc((unsigned int)numEl, sizeof(double));
  emx->numDimensions = numDimensions;
  emx->allocatedSize = numEl;
  return emx;
}

Upvotes: 0

Views: 483

Answers (1)

Aconcagua
Aconcagua

Reputation: 25516

int(*)[2] is not a command - it declares a pointer to an int-array of length 2.

Now let's have a look at this: *(int (*)[2])&iv0[0]. First, the address of the first element of iv0 is taken, type is int*, this is converted into a pointer to int[2] (i. e. int(*)[2]), which is then dereferenced again, getting back an int[2]. This is promoted to an int* again when passed to emxCreateND_real_T.

Actually, the same would have happened if you simply would have passed iv0 directly...

result = emxCreateND_real_T(2, iv0);

And yes, for a 10x5 matrix, you would initialize static int iv0[] = { 10, 5 };

Upvotes: 3

Related Questions