C Programming - Memory Allocation - Discussion
Discussion Forum : Memory Allocation - Find Output of Program (Q.No. 6)
6.
Assume integer is 2 bytes wide. What will be the output of the following code?
#include<stdio.h>
#include<stdlib.h>
#define MAXROW 3
#define MAXCOL 4
int main()
{
int (*p)[MAXCOL];
p = (int (*) [MAXCOL])malloc(MAXROW *sizeof(*p));
printf("%d, %d\n", sizeof(p), sizeof(*p));
return 0;
}
Discussion:
24 comments Page 2 of 3.
Ashish kumar said:
1 decade ago
Because total memory allocate is 24 byte. But p allocate the first block of memory.
Arjun said:
1 decade ago
Why does the line p = (int (*) [MAXCOL])malloc(MAXROW *sizeof(*p)); has no effect?
Rutuja said:
1 decade ago
@Ritu.
Here sizeof (*p) indicates size of data which is pointed by p which is (2*4) =8.
And sizeof (p) indicates size of integer pointer p which is 2.
Here sizeof (*p) indicates size of data which is pointed by p which is (2*4) =8.
And sizeof (p) indicates size of integer pointer p which is 2.
Xyz said:
1 decade ago
p is a pointer pointing to array of intergers of size 4
As size of integer is 2 bytes then it becomes totally 2*4=8 bytes
i.e sizeof(*p) = 8 bytes
As size of integer is 2 bytes then it becomes totally 2*4=8 bytes
i.e sizeof(*p) = 8 bytes
Hari said:
1 decade ago
"*" indicates address of the pointer
Ritu said:
1 decade ago
What does "*" indicates there?
Durgam_anil said:
1 decade ago
p is a pointer pointing to array of intergers of size 4
As size of integer is 2 bytes then it becomes totally 2*4=8 bytes
i.e sizeof(*p) = 8 bytes
where as
sizeof(p) = 2 bytes as p is integer as holds the address in unsigned integer form.
As size of integer is 2 bytes then it becomes totally 2*4=8 bytes
i.e sizeof(*p) = 8 bytes
where as
sizeof(p) = 2 bytes as p is integer as holds the address in unsigned integer form.
Nirbhay singh said:
1 decade ago
A pointer which hold address always takes 4 byte(linex)
sothat sizeof(p) gives 4
sothat sizeof(p) gives 4
Divya said:
1 decade ago
thanks
Sundar said:
1 decade ago
The given answer is exactly correct.
In Turbo C under DOS (16 bit OS), the size of the integer is 2 bytes. So, if you run the above code in Turbo C the output will be 2, 8.
If you run the same code in Linux (32 bit OS) the output will be 4, 16. Because the size of the integer in Linux is 4 bytes.
I have tested in both Turbo C (in DOS) and GCC (in Linux).
I hope this will help you. Have a nice day!
In Turbo C under DOS (16 bit OS), the size of the integer is 2 bytes. So, if you run the above code in Turbo C the output will be 2, 8.
If you run the same code in Linux (32 bit OS) the output will be 4, 16. Because the size of the integer in Linux is 4 bytes.
I have tested in both Turbo C (in DOS) and GCC (in Linux).
I hope this will help you. Have a nice day!
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers