简体   繁体   English

如何使可变大小的2d数组指向(并表示)c中1d数组的起始地址?

[英]How can I make a variable size 2d array point to (and represent) the starting address of a 1d array in c?

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). 但是回想起来,这是毫无意义的,因为float **会如何神奇地知道我想要[n / p] [n]的行,列分布(我不认为这样做,因为程序在aIn2D的首次访问时就崩溃了)。

So does anyone know how to do something like float aIn2D[n/p][n] = &A; 所以有人知道如何做类似float aIn2D [n / p] [n] =&A;的操作吗? in c? 在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. 编辑:还有一件事,我确定知道[n / p] [n]的大小将是A持有的数据量的大小。

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. edit2:一个非常重要的方面是两个数组都指向相同的内存位置,aIn2D只是让我轻松地在随后的方法中访问A的一种方式。

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. 假设n_rows和n_cols是变量,假设您有一个n_rows * n_cols 1D浮点数组,您想将其视为n_rows x n_cols 2D数组。

With C99, which supports variable-sized arrays, you actually can do pretty much what you want: 使用支持可变大小数组的C99,您实际上可以完成几乎所有您想做的事情:

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);

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM