0
votes

I'm trying to declare a long 2-dimensional array like this, so i can later copy the long array into the small array that's the right size:

double arr_long[MAX][2]; double arr[][];

so i can later use:

arr = malloc(amount*sizeof(double[2]));

and then copy all the elements over. (i'm filling the long array with a simple for loop) But my compiler gives me an Error, saying "array type has incomplete element type" about the declaration. Is there no way to declare a multidimensional array without specifying its size?

2
You can do a pointer to an array of 2. double (*arr)[2]. But it's just easier to just struct something { double elements[2]; } with struct something *arr;KamilCuk

2 Answers

1
votes

Is there no way to declare a multidimensional array without specifying its size?

You have to know all dimensions except the "last"/the most "upper" dimension. Because to allocate memory you have to know the size of the element in the array. As for your case it's simple - you allocate an array of two doubles.

You can do a pointer to an array of 2 double elements:

double (*arr)[2];
// you can normally allocate
arr = malloc(sizeof(*arr) * amount);
// and normally iterate
for (size_t i = 0; i < amount; ++i) {
  for (size_t j = 0; j < 2; ++j) {
     printf("%f", arr[i][j]);
  }
}

The type of *arr is double[2], so the sizeof(*arr) will properly resolve as sizeof(double[2]).

1
votes

You are trying to change the value of arr ( where this is pointing to) this an error because this type of a pointer cannot be repointed to something else unless it was an parameter. You can think of it as an const variable. Which you can't change its value. You could do as follows:

double * arr [2] ;

And then you invoke malloc .... and if do not want to give it any size, then you could use pointer to pointer to double. as follows:

double ** arr;

and then invoke malloc like this

arr = (double **) malloc(sizeof(double *) * max);

so here you have an arr of pointer which are not pointing to anything, if you want them to do that, you should allocate memory for each one as follows:

for (int i = 0; i < max; i++){
   arr[i] = malloc(sizeof(double) * 2);
}