Reputation: 73
I'm trying to do something as followed
float* A = fill_float(); //in other words A is full
float aIn2D[n/p][n] = &A; //the 2d array should be able to alter the 1d
I tried the above but wouldn't compile (something about not being able to make the size variable length?). also tried
float** aIn2D = &A
But in retrospect that was nonsensical as how would the float** magically know I want a row, column distribution of [n/p][n] (i don't think it does since the program crashes right at the first access of aIn2D).
So does anyone know how to do something like float aIn2D[n/p][n] = &A; in c?
edit: One more thing, I for sure know the size from [n/p][n] is going to be the size of the amount of data A is holding.
edit2: A very big aspect is that both arrays point to the same memory location, aIn2D is just a way for me to easily access A in methods that follow.
Upvotes: 1
Views: 123
Reputation: 64308
Assuming n_rows and n_cols are variables, let's say you have an n_rows*n_cols 1D array of floats that you want to treat as an n_rows x n_cols 2D array.
With C99, which supports variable-sized arrays, you actually can do pretty much what you want:
float* A = fill_float();
float (*aIn2D)[n_cols] = (float (*)[n_cols])A;
Otherwise, you can do something like this:
float *A = fill_float();
float **aIn2D = malloc(n_rows*sizeof(float*));
{
int i=0;
for (; i!=n_rows; ++i) {
aIn2D[i] = A + i*n_cols;
}
}
// Use aIn2D[row][col]
free(aIn2D);
Upvotes: 1
Reputation: 9204
If you want to convert 2-D array to 1-D then you should try like this :
float a[MAX];
float dup_a[ROW][COL];
int i,j,k;
for(i = 0 ; i < MAX ; i++)
{
j= i / ROW ; // you can do it by i / COL also
k= i % ROW ; // you can do it by i % COL also
dup_a[j][k] = a[i];
}
Or, you can try this ,
float* A = fill_float();
float (*aIn2D)[n] = &A; // create a pointer to an array
Upvotes: 0