I'm studying C and have some question about dynamic memory allocation syntax.
The code below is an example of dynamic memory allocation. If I understand correctly
(char *) malloc (50 * sizeof (char));
will return a pointer to a data type of char and
pr = (char *) malloc (50 * sizeof (char));
will assign the pointer 'pr' to the pointer declared when allocating dynamic memory. So we will have a pointer point to another pointer
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *pr;
pr = (char*)malloc( 50 * sizeof(char) );
return 0;
}
I still have a hard time understanding the syntax used to allocate dynamic memory. Can someone explain in detail? thank you
will assign the pointer 'pr' to the pointer declared when allocating dynamic memory. So we will have a pointer point to another pointer
No, you'll have the value of the pointer variable stored.
This is just the same as
int x = 5;
or, in a more complex case
int test(void) { return 5;}
int x = test();
in this case, test()
returns a value 5
, which is assigned to x
. Same way
char * pr = malloc (50 * sizeof (*pr)); // no casting, and sizeof (*pr) is a
// more robust way to have the size defined
assigns the returned pointer by malloc()
to pr
. There's no pointer to pointer here.
In other words, pr
holds the pointer which points to the memory location allocated by the call to malloc()
, or a NULL
(null-pointer constant) in case the call failed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With