Accessing elements of typedef'ed array of pointers
arrays, c, c++, pointers
Solution
I believe what you're looking for is the following...
#define N 128
#define ELEMENTS 10
typedef int* arrayOfNPointers[N];
arrayOfNPointers myPtrs = { 0 };
int i;
for (i=0; i<N; i++) {
myPtrs[i] = malloc(sizeof( int ) * ELEMENTS);
}
You want arrayOfPointer to be an array of N pointers to ELEMENTS integers. Also, when you malloc() the space for your integers, you need to multiply the number of ELEMENTS by the size of an integer. As it is, the space you're allocating is too small to hold the data you're trying to store in it.
Your typedef declared arrayOfPointer as a pointer to an array of N integers. Remember to use the right-left reading rule to understand what you are declaring a variable/type to be. Because you had `(*arrayOfPointer)` in parens there was nothing to the right and a pointer to the left, so arrayOfPointer is a pointer TO `[N]` (right) int (left). Not what you intended.
Also... do not cast malloc() in C!
Problem
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?