C Access Memory: Dynamic Memory Access in C
Learn how to efficiently access and manipulate dynamic memory in C programming. Understand the role of pointers and how dynamic memory behaves similarly to arrays, enabling you to retrieve elements by referring to their index numbers.
C Access Memory
Access Dynamic Memory
Dynamic memory behaves like an array, with its data type specified by the type of the pointer. As with arrays, to access an element in dynamic memory, refer to its index number:
Syntax
ptr[0] = 25;
You can also dereference the pointer to access the first element:
Syntax
*ptr = 25;
Example: Read and Write to Dynamic Memory
This example demonstrates how to allocate dynamic memory, write to it, and read from it:
Syntax
// Allocate memory
int *ptr;
ptr = calloc(5, sizeof(*ptr));
// Write to the memory
*ptr = 10;
ptr[1] = 20;
ptr[2] = 30;
ptr[3] = 40;
// Read from the memory
printf("%d\n", *ptr);
printf("%d %d %d %d", ptr[1], ptr[2], ptr[3], ptr[4]);
Output
10
20 30 40 0
A Note About Data Types
Dynamic memory does not have its own data type; it is just a sequence of bytes. The data in the memory can be interpreted as a type based on the data type of the pointer.
In this example, a pointer to four bytes can be interpreted as one int
value (4 bytes) or as an array of 4 char
values (1 byte each).
Example: Interpreting Memory as Different Data Types
Syntax
int *ptr1 = malloc(4);
char *ptr2 = (char*) ptr1;
ptr1[0] = 1936287828;
printf("%d is %c %c %c %c", *ptr1, ptr2[0], ptr2[1], ptr2[2], ptr2[3]);
Output
1936287828 is X Y Z W