I am trying to build two dimensional array by dynamically allocating. My question is that is it possible that its first dimension would take 100 values, then second dimension would take variable amount of values depending on my problem? If it is possible then how I would access it? How would I know the second dimension's boundary?
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
I believe the OP wants a single chunk of memory for the array, and is willing to fix one of the dimensions to get it. I frequently like to do this when coding in C as well.
We all used to be able to do
double x[4][];
and the compiler would know what to do. But someone has apparently messed that up - maybe even for a good reason.The following however still works and allows us to use large chunks of memory instead of having to do a lot of pointer management.
The trick is to declare the fixed dimension in a struct. But keep in mind that the "first" dimension is the dynamic dimension and the "second" one is fixed. And this is the opposite of the old way ...
You will have to track the size of your dynamic dimension on your own - sizeof can't help you with that.
Using anonymous thingies you might even be able to git rid of 'y'.
You can use array of 100 pointers:
int *arr[100];
then you can dynamically allocate memory to each of the 100 pointers separately of any size you want, however you have to remember how much memory (for each pointer) you have allocated, you cannot expect C compiler to remember it or tell it to you, i.e.
sizeof
will not work here.To access any (allowed, within boundary) location you can simply use 2D array notation e.g. to access
5th
location of memory allocated to20th
pointer you can usearr[20][5]
or*(arr[20] + 5)
.Using a single pointer:
/* how to access array elements */
Using pointer to a pointer:
In this case you can access array elements same as you access statically allocated array.
(See the comments in the code)
As a result you'll get an array such like the following: