S
Salman Khilji
After reading all the FAQs, I cannot solve the following problem:
I have a pointer of type double. I am supposed to
1) Allocate memory for it assuming that the pointer will be pointing
to a multi-dimensional array whose dimensions will be specified at
run-time.
2) Set the individual elements of the array using pointer-arithmetic.
I can do 1) but 2) is hard and requires some recursive logic that I
cannot come up with.
Suppose we are given the dimensions of a multi-array using a 1D array
of length D. For example, [2 3] means that we are dealing with a
multi-array of 2x3 and[2 3 5] would mean the array in question is
2x3x5. Someone calls a function like the following to tell us that.
void setArrayDim(int arrayDim[], int size, int elemSize);
Assming that the multi-array's element type is T.
1) is solved by:
malloc( product of all elements of arrayDim * sizeof(double) );
For 2), we have another function like:
setArrayValue(arrayIndices[], int size, double value);
In this case the arrayIndices array has the indices into which value
must be deposited. We somehow have to come up with an equation that
computes the correct pointer location.
I can do this manually for a 2D array. Maybe a 3D array won't be
hard. But what I need to do is a multi-dimensional array of
dimensions D.
I have a pointer of type double. I am supposed to
1) Allocate memory for it assuming that the pointer will be pointing
to a multi-dimensional array whose dimensions will be specified at
run-time.
2) Set the individual elements of the array using pointer-arithmetic.
I can do 1) but 2) is hard and requires some recursive logic that I
cannot come up with.
Suppose we are given the dimensions of a multi-array using a 1D array
of length D. For example, [2 3] means that we are dealing with a
multi-array of 2x3 and[2 3 5] would mean the array in question is
2x3x5. Someone calls a function like the following to tell us that.
void setArrayDim(int arrayDim[], int size, int elemSize);
Assming that the multi-array's element type is T.
1) is solved by:
malloc( product of all elements of arrayDim * sizeof(double) );
For 2), we have another function like:
setArrayValue(arrayIndices[], int size, double value);
In this case the arrayIndices array has the indices into which value
must be deposited. We somehow have to come up with an equation that
computes the correct pointer location.
I can do this manually for a 2D array. Maybe a 3D array won't be
hard. But what I need to do is a multi-dimensional array of
dimensions D.