Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing elements of typedef'ed array of pointers

I'm having some issues accessing elements of an array passed into a function.

#define N (128)
#define ELEMENTS(10)
typedef int (*arrayOfNPointers)[N];

So, if this is right, it is a data type describing an array of N pointers to int.

I later initialize my arrays individually, like so:

arrayOfNPointers myPtrs = { 0 };
int i;
for (i=0; i<N; i++) {
  myPtrs[i] = (int*)malloc(ELEMENTS);
}

However, this fails with the following error:

error: incompatible types when assigning to type 'int[128]' from type 'int *'

So, it seems there is something very wrong in my syntax. But in another chunk of code, where I'm modifying the contents of some such structures, I have no problems.

void doWork(void* input, void* output) {
   int i,m,n;
   arrayOfNPointers* inputData = (arrayOfNPointers*)input;
   int* outputData = (int*)output;

   for (m=0, n=0; n<nSamples; n++) {
      for (i=0; i<nGroups; i++) {
         outputData[m++] = (*inputData)[i][n];
      }
   }
}

Is this array logic severely broken?

like image 428
Cloud Avatar asked Dec 04 '25 00:12

Cloud


1 Answers

typedef int (*arrayOfNPointers)[N];

So, if this is right, it is a data type describing an array of N pointers to int.

I think this is a pointer to an array of N integers and not an array of N pointers to integers....

This means that that the following line doesn't behave as your expecting... myPtrs[i] = (int*)malloc(ELEMENTS); Because myPtrs is a pointer to an N-dimensional array (in this case an array of 128 ints), myPtrs[i] is the i-th n-dimensional array. So you are trying to assign a pointer to an array, which is why you get the msg...

error: incompatible types when assigning to type 'int[128]' from type 'int *'

like image 116
Jimbo Avatar answered Dec 06 '25 15:12

Jimbo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!