| rachitagrawal (98) | |||||
How to pass a sub 2-D array to a function. For e.g. given the array below
In a function F. I want to access the bottom right of the array just
So how to do that? Can someone help me out in this? | |||||
|
|
|||||
| Scipio (442) | |||||
Considering array's as constant pointers, you can simply pass the array and the sizes:
Now we have our array in the function (notice that, because arrays are constant pointers, chances in the elements inside the function will be the same for the elements of the original array). It's now simple to access for example the botton right:
| |||||
|
Last edited on
|
|||||
| rachitagrawal (98) | |
| I want to access them as a[0][0], a[0][1] and so on. So, in the case above, I should get a[0][0] = 7, a[0][1]= 8, a[1][0]=11 and a[1][1] = 12. | |
|
|
|
| Scipio (442) | |
You can use the for-loop is posted to store the value's into another array, but it isn't really necessary. array[x+somevalue]; isn't much harder to understand as array[x];, IMO.
| |
|
|
|
| Disch (7385) | |||||
|
Ugh @ multidimensional arrays. I don't know why everybody likes them so much. Syntax hell. Re Scipio:
This wouldn't work. myArray is not a two stage pointer, it's a 2D array, which is stored the same as a 1D array, just with syntax differences (so it's a one stage pointer, not 2) The way to do this would be:
Notice that the size of the lowest element(s) must be known and constant. Only the first pair of brakets can remain empty. You cannot pass the sizes to the function as Scipio suggested (well I suppose you could but it wouldn't make much sense for the lower brakets). That is only possible when the array is created dynamically (in which case it is a two stage pointer, and Scipio's example would be correct). Or... you could template the function to make the sizes more dynamic. However that is a bit more complicated and seems like overkill for this. EDIT: Doh I totally missed the whole "sub array" thing. XD. Something similar to what Scipio suggested is probably the best way to go, here. Due to the way these arrays are stored, you can't just extract an arbitrary group of them with a single pointer. Either work with the array in full, or make a class to abstract this behavior. | |||||
|
Last edited on
|
|||||
| Bazzy (6275) | ||||
You can use the template trick:
for the sub array, you can create a new array in the function and setting its elements to the corresponding of the passed array eg: yourNewArray[0][0] = yourArgumentArray[1][2];
| ||||
|
|
||||