C Programming - Memory Allocation - Discussion
Discussion Forum : Memory Allocation - Point Out Correct Statements (Q.No. 1)
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;
}
Discussion:
17 comments Page 2 of 2.
Bhargav said:
1 decade ago
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.
Saksham said:
1 decade ago
@pragya Type casting (int(*)[3]) will not increase the size. So it's just 18 bytes!
Tofik Kacchi said:
1 decade ago
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.
Then again reallocating using malloc will create another array of size 3.
Therefore, its p[3][3].hence we require 2 nested for loop.
Pragya said:
1 decade ago
@ 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.
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.
Teju said:
1 decade ago
Does
p = (int(*)[3])malloc(3*sizeof(*p));
allocates 54 bytes of memory ? Anyone please explain.
p = (int(*)[3])malloc(3*sizeof(*p));
allocates 54 bytes of memory ? Anyone please explain.
Gopi said:
1 decade ago
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] .
p = (int(*)[3])malloc(3*sizeof(*p));
and again we are allocating more memory to it so like p[3][3] .
Bhavi said:
1 decade ago
Please give explanation to this program.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers