开发者

2d array in C. Fixed width but unknown height?

Is it possible to make an array with an unknown height but a set width?

So that It can be something like:

|----------8-----------|

[0][0][0][0][0][0][0][0]  |
[1][1][1][1][1][1][1][1]  |
[2][2][2][2][2][2][2][2]  |
[3][3][3][3][3][3]开发者_StackOverflow中文版[3][3] \|/

So that it can be as big as it needs but stays 8 floats wide.

I have a feeling that the declaration will look somewhat like:

    float *array[8] // maybe???

or

    float array[8][] // idk???

Im not used to multiple pointers on a var (I get confused still). I use apple's cocoa framework a lot so I would normally use NSArray but the thing I'm building requires a C-based array not a class.


Try this:

float (*array)[8];

...which declares array as a pointer to 8-element arrays of float.

You can then allocate space for the whole thing as follows:

array = malloc(sizeof(*array) * num_elements);

Then, array[3][0], for example, would access the first float in the 4th array of 8 floats.


float *array[8];

Now you have an array of 8 float pointers.

For each one of these, you would then need to allocate space when you know how large it needs to be:

array[0] = calloc(numMembers, sizeof(float));

If you later decided you needed a specific second dimension to be larger, you would need to reallocate.


Yes It definatly is:

  float *p2DArray[8];

  for (int i = 0; i < HEIGHT; ++i) {
    p2DArray[i] = (float*)malloc(sizeof(float)*WIDTH);
  }

taken from Multi-Dimensional Arrays


As an argument to a function, you can require a 2d array of unknown height, as so

void foo(int arr[][8])
{
     //...do stuff with arr...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜