Dynamic memory, akin to arrays, adopts a structure where its data type corresponds to the type of the pointer; similarly, accessing an element within dynamic memory involves referencing its index number:
ptr[0] = 12; |
Accessing the first element can also be achieved by dereferencing the pointer.
*ptr = 12; |
Perform reading from and writing to dynamic memory:
// Allocate memory int *ptr; ptr = calloc(4, sizeof(*ptr)); // Write to the memory // Read from the memory |
Dynamic memory lacks its inherent data type and is simply a stream of bytes. The interpretation of data within the memory depends on the data type associated with the pointer.
For instance, a pointer pointing to four bytes can be construed either as a single int value (occupying 4 bytes) or as an array of four char values (each occupying 1 byte).
int *ptr1 = malloc(4); char *ptr2 = (char*) ptr1; ptr1[0] = 1684234849; printf(“%d is %c %c %c %c”, *ptr1, ptr2[0], ptr2[1], ptr2[2], ptr2[3]); |