'Unable to access values while passing 2-D pointer
I have the following code :
int allocationMatrix[2+ 1][1+ 1];
allocationMatrix[0][0] = 2;
allocationMatrix[0][1] = 1;
buildAllocationMatrix(flowNProcess, allocationMatrix);
The buildAllocationMatrix function is declared like:
void buildAllocationMatrix(FlowNProcess *flowNProcess, int *allocationMatrix)
inside it, if I check the value of *(allocationMatrix+1), it gives 0 but the assignment
before calling the function is allocationMatrix[0][1] = 1; Not sure why its giving 0
It should return 1. What could be the reason for this?
Solution 1:[1]
- Pass
int **allocationMatrixinside function since it is 2D array.
(becauseint *allocationMatrix is interpreted as passing address of 1D array) .
- And access it by
*(*(allocationMatrix+0)+1).
(Reason: by using*(allocationMatrix+0) you will get address of 0th row and in order to get address of 0th row 1st column we can use (*(allocationMatrix+0)+1) thus to get element of that position dereference it as
*(*(allocationMatrix+0)+1) ).
While accessing you can skip zero.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
