0

Memory allocation

Hi, some enlightment... Could someone... int *ptr; /* a block of 10 ints */ ptr = malloc(10 * sizeof(*ptr)); if (ptr != NULL) { *(ptr + 2) = 50; /* assign 50 to third int */ } *ptr = 40 bytes... 10*40.... 400 allocated... Ptr is null, despite...? (Ptr + 2) pointer? Ptr takes the value, index...? Tks.

15th Jan 2020, 2:13 PM
Ivan Zanoth
Ivan Zanoth - avatar
6 Réponses
+ 1
Wait.. Already... Ignore about the ptr address... The variable itself have an address, what is not the same that pointers.. Ok..
15th Jan 2020, 2:35 PM
Ivan Zanoth
Ivan Zanoth - avatar
0
I didn't understand your question
15th Jan 2020, 2:18 PM
Ipang
0
Which part of this code you need help with? the `if` part, the `malloc` part, the pointer arithmetic part?
15th Jan 2020, 2:22 PM
Ipang
0
Yes.... Despite alloc, is null? Why ptr is allocated with memory, and no your adress? And the pointer arithmetic... :) Tks in addition!
15th Jan 2020, 2:28 PM
Ivan Zanoth
Ivan Zanoth - avatar
0
int *ptr; // define a pointer of int ptr = (int*)malloc(10 * sizeof(int)); // allocate memory block, big enough to contain 10 int value // assign the memory block address for <ptr> variable if (ptr != NULL) { // ptr will be NULL if malloc failed in allocating memory // ptr != NULL here means memory allocation succeeded *(ptr + 2) = 50; // set the third int value to 50 }
15th Jan 2020, 2:44 PM
Ipang
- 1
Hi tks for ask... Some enlightment about the expression, basically.
15th Jan 2020, 2:19 PM
Ivan Zanoth
Ivan Zanoth - avatar