Civil Engineering Mechanical Engineering Chemical Engineering Networking Database Questions Computer Science Basic Electronics Digital Electronics Electronic Devices Circuit Simulation Electrical Enigneering Engineering Mechanics Technical Drawing

# C Programming - Memory Allocation - Discussion

@ : Home > C Programming > Memory Allocation > Point Out Correct Statements - Discussion

"Loneliness is the most terrible poverty."
- Mother Teresa
1.

Point out the correct statement will let you access the elements of the array using 'p' in the following program?

``````#include<stdio.h>
#include<stdlib.h>

int main()
{
int i, j;
int(*p)[3];
p = (int(*)[3])malloc(3*sizeof(*p));
return 0;
}
``````

 [A]. ``````for(i=0; i<3; i++) { for(j=0; j<3; j++) printf("%d", p[i+j]); } `````` [B]. ``````for(i=0; i<3; i++) printf("%d", p[i]); `````` [C]. ``````for(i=0; i<3; i++) { for(j=0; j<3; j++) printf("%d", p[i][j]); } `````` [D]. ``````for(j=0; j<3; j++) printf("%d", p[i][j]); ``````

Explanation:

No answer description available for this question.

 Bhavi said: (Sun, Nov 14, 2010 01:21:58 PM) Please give explanation to this program.

 Gopi said: (Fri, Jan 21, 2011 10:22:36 AM) Here, int(*p)[3]; //its like p[3] p = (int(*)[3])malloc(3*sizeof(*p)); and again we are allocating more memory to it so like p[3][3] .

 Teju said: (Sat, Aug 20, 2011 11:32:19 AM) Does p = (int(*)[3])malloc(3*sizeof(*p)); allocates 54 bytes of memory ? Anyone please explain.

 Pragya said: (Fri, Oct 7, 2011 04:05:00 AM) @ Teju Yes. It allocates 54 bytes because sizeof(*p)=6 bytes So 3 * 6 = 18 bytes and then int (*)[3] points to an array of 3 blocks each having 18 bytes. So p = (18 + 18 + 18) = 54 bytes.

 Tofik Kacchi said: (Tue, Mar 20, 2012 03:03:17 PM) Here initially *p[3] will statically create an array of p[3]. Then again reallocating using malloc will create another array of size 3. Therefore, its p[3][3].hence we require 2 nested for loop.

 Saksham said: (Fri, Jun 8, 2012 09:59:33 AM) @pragya Type casting (int(*)[3]) will not increase the size. So it's just 18 bytes!

 Bhargav said: (Fri, Dec 7, 2012 01:16:35 AM) Here type casting and it is array of pointers. So we have to access by using double pointer. So option C p[i][j] is similar to that.