Multidimensional Array in a Structure

This is a discussion on Multidimensional Array in a Structure within the C Programming forums, part of the General Programming Boards category; Hi,
I have a structure in which I want to hold various data and a 2D array. Since I have ...

Multidimensional Array in a Structure

Hi,

I have a structure in which I want to hold various data and a 2D array. Since I have to wait for user input before deciding the array size, I can't declare it directly in the structure. Also, I know that microsoft enables us to declare unsized arrays in a structure but the Linux machines on which I work do not allow it.

At first I just tried declaring a pointer and then assigning my array to it. This works when I want to attach a 1D array but it returns an incompatible pointer assignement with a 2D array. I was wondering what I could do. Stuff like **array does not work either (I had to try it lol).

I don't have a lot of experience in C so I would appreciate it if you could be as explicit as possible.

This makes a lot of sense. I tried using malloc but I did not really know what I was doing so I only used it once which only made it behave like a 1D array.

The parts where you use

sizeof(p->datatype *)
and
sizeof(p->datatype)

did not work for me. The 2D array I have is made up of another structure that I called block. So when I tried with block instead of datatype I got a "structure has no member named `block' " error. I replaced then by the name i had given to the block declaration (block_array in my case) and that simply gave me parse errors.

But since by that time I had determined the number of rows and columns I would need I used

sizeof(block)*nb_rows*nb_columns
and
sizeof(block)*nb_columns

and it seems to work fine. I want to thank you for the prompt response and the good example code. It made me understand malloc instantly.

Where 'datatype' is the type of data, such as an integer, double, etc.

So just remove the "p->" part in front of where I have "p->datatype" in my example, and replace the word "datatype" with whatever type your array is going to be.

But no, you don't want "sizeof( block ) * nb_rows * nb_ columns", because that will allocate that many block instances. It's not the correct way to do it. Because that will treat it as one long single dimension array, which isn't techincally accurate.