By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,194 Members | 889 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,194 IT Pros & Developers. It's quick & easy.

Dynamic memory allocation

P: 3
Can anyone please explain me the meaning of the declaration&allocation

(1) int (*ptr)[4];


(2) ptr = (int(*)[4]) malloc (2*sizeof(int));

printf("\n <%d> <%d>", sizeof(ptr), sizeof(*ptr));

I got the answer 4 and 16.

(3) How sizeof(*ptr) become 16?

(4) The above allocation is 2x4 array or 4x2 array?
Sep 29 '06 #1
Share this Question
Share on Google+
1 Reply


Banfa
Expert Mod 5K+
P: 8,916
(1) int (*ptr)[4];

This declares a pointer to an array of 4 integers


(2) ptr = (int(*)[4]) malloc (2*sizeof(int));
This is an error variable ptr points to an array of 4 integers but you have only allocated an array of 2 integers. Using sizeof *ptr in malloc will get you the correct amount of data no matter what pointer is.

printf("\n <%d> <%d>", sizeof(ptr), sizeof(*ptr));

I got the answer 4 and 16.

(3) How sizeof(*ptr) become 16?


ptr is a pointer and clearly on you machine pointers are 4 bytes hence 4. I would say on your machine that ints are 4 bytes, ptr is a pointer to an array of 4 integers, the size of an array of 4 integers is 4 * sizeof(int) = 4 * 4 = 16.

Note that sizeof works of the size of the variables declared type, not the amount of memory you allocated to it.

(4) The above allocation is 2x4 array or 4x2 array?
No it allocates a 1 x 2 array, the pointer is expecting a 1 x 4 array.
Sep 29 '06 #2

Post your reply

Sign in to post your reply or Sign up for a free account.