C Programming - Memory Allocation - Discussion

Discussion Forum : Memory Allocation - Point Out Correct Statements (Q.No. 4)
4.
Point out the correct statement which correctly allocates memory dynamically for 2D array following program?
#include<stdio.h>
#include<stdlib.h>

int main()
{
    int *p, i, j;
    /* Add statement here */
    for(i=0; i<3; i++)
    {
        for(j=0; j<4; j++)
        {
            p[i*4+j] = i;
            printf("%d", p[i*4+j]);
        }
    }
    return 0;
}
p = (int*) malloc(3, 4);
p = (int*) malloc(3*sizeof(int));
p = malloc(3*4*sizeof(int));
p = (int*) malloc(3*4*sizeof(int));
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
9 comments Page 1 of 1.

Merry said:   8 years ago
Can someone tell me what 3 and 4 in that statement stands for.

Mfranc said:   10 years ago
I fully agree with @N N. If we assume language C then option C is more correct. Of course D will work as well, but it's going against the language and compiler. And since this was supposed to be test for C and not C++, I'm surprised by this (in a rather negative sense).
(1)

Simar Sidana said:   1 decade ago
Can someone explain the output of this program?

Anubhav said:   1 decade ago
OF COURSE, in C, both the options c and d are correct but for c++ only option d is correct because there is a matter of type casting in c++ in such a case.
(1)

Narendar said:   1 decade ago
Without typecast also it will execute. Because C doesn't consider the typecasting in case of malloc. Whereas in C++ it is mandatory to typecast.
(1)

Nidhinpradeep said:   1 decade ago
In this array there is 3*4 elements. So memory to be allowed is 3*4*sizeof(int) ;
(1)

Manu said:   1 decade ago
Actually, malloc return a generic pointer so we have to typecast it. We are using integer so it is typecast as an integer.

Now, since 2d array is also stored in memory like 1d array, 3*4=12 size is created through malloc.

So D is right.
(1)

N n said:   1 decade ago
Typecasting malloc is an issue in C++, not C.

See: http://c-faq.com/malloc/mallocnocast.html
(1)

Vijay said:   1 decade ago
Please tell me its explanation.

Post your comments here:

Your comments will be displayed after verification.