Curriculum
Course: C basic
Login

Curriculum

C basic

C Introduction

0/1

C Get Started

0/1

C Comments

0/1

C Constants

0/1

C Operators

0/1

C Break and Continue

0/1

C User Input

0/1

C Memory Address

0/1

C Structures

0/1
Text lesson

C Access Memory

Access Dynamic Memory

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;

Example

Perform reading from and writing to dynamic memory:

// Allocate memory
int *ptr;
ptr = calloc(4, sizeof(*ptr));

// Write to the memory
*ptr = 2;
ptr[1] = 4;
ptr[2] = 6;

// Read from the memory
printf(“%d\n”, *ptr);
printf(“%d %d %d”, ptr[1], ptr[2], ptr[3]); 

A note about data types

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).

Example

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]);