View Full Version : 2D Array in 1D fashion
anon10038
07-04-2012, 03:20 AM
Dear Sir,
We are facing problem in accessing 2D array in 1D fashion. Please suggest the possible steps to solve this problem.
Thanks,
anon10041
07-04-2012, 03:30 AM
Sir,
We were actually trying to use * operator to access 2D array in 1D fashion, but unfortunately, instead of getting the values, we were getting the memory addresses as outputs. Moreover, we are facing problem in implementing Row Major concept in this question.
Thanks,
Anon10041
Anon10038/Anon10041,
I will need more details here. The name of a 2D array is a double pointer i.e. int a[1][2] has a's type as int **a. You will need to de-reference it twice to see the value. Also note that a[1] is of type int *.
Thanks,
Anup
anon10038
08-04-2012, 12:35 AM
Sir,
You have given the answer, will use int * and will increment it with one till the total number of elements are processed.
thanks, :)
anon10110
27-08-2012, 04:15 PM
Sir,
I have tried this,but i am not sure wheather it is the right way to access the elements.Can you please tell wheather this code is okay or not?
I have used the formula of A[i][j] = *(A[i]+ j) = *(*(A+i)+j) .
Thanks218
Anon10110,
You can check the results yourself and see whether they match. First access the elements using A[i][j] and then using your formulat.
Thanks,
Anup
anon10110
27-08-2012, 04:57 PM
Sir,
They are running fine but i was confused because i did not followed any memory allocation to the pointers and about the correctness of the way the program is written.
Thanks
Anon10110,
Can you tell me exactly what you did and what it is that you are asking? I am unable to comprehend the exact question and we typically do not entertain "Is my program correct" kind of questions.
Thanks,
Anup
anon10110
27-08-2012, 05:22 PM
Okay sir,
I have cleared that doubt now.Sir there are some things i wanted to ask you in the same context of pointer which are as follows.
1)What did you meant when you say in slide of pointer to pointer "We created a sort of array with first index as 2 and second index as 3?
2)In the output it is written *p-1 and *p-1-1 whearas you read them as *p+1 and *p+1+1.
Please help me in understanding them.
Thanks219
Thanks
Anon10110,
For (1), please look at the code and the mallocs. You will notice that we first allocation 2 spaces for a int ** and then to the first of this location, we allocate, a location of size '3', is this not similar to a 2-D array?
For (2), you need to look at the source code and what is being given as argument to the printf, the answer is there itself.
Thanks,
Anup
anon10110
27-08-2012, 05:41 PM
Sir,
That explains a lot. :)
Thanks