Hello list ...
I think I'm grokking it - but please critique the following code and comments therein:
Code:
/*
program to demonstrate the use of pointers and
malloc to dynamically allocate memory.
Remember these rules:
1. Always assign an address to a pointer before using it!
2. Conversely, never assign a value to *some_ptr without first
assigning an address to some_ptr!
*/
#include <stdio.h>
#include <malloc.h>
//insert function prototypes below
int main( void )
{
int *ptr2_int;
ptr2_int = (int *) malloc(sizeof(int));
/* Breakdown of the above line:
sizeof(int) => returns the number of bytes that a variable
of type "int" requires.
malloc(some_number) => grabs "some_number" of consecutive
bytes of the available (unused) memory
on the target machine. Returns the starting
address of those bytes.
(int *) => This is "type casting". It says that the starting address
of the available memory will be a pointer to data that will be
of type "int".
In short:
"allocate from RAM enough space for a variable of type "int". Then assign
the starting address of that memory to ptr2_int, which is a pointer to data
of type "int"
*/
*ptr2_int = 999;
printf ("content of ptr2_int: %p\n", ptr2_int);
printf ("value pointed to by ptr2_int: %d\n", *ptr2_int);
return 0;
}
Much obliged!
--
Duke