Here we will learn what is dynamic memory allocation in C language. The C programming language provides several functions for memory allocation and management. These functions can be found in the
Function | Description |
---|---|
This function allocates an array of | num elements, with the size of each element in bytes. |
This function releases a memory block specified by the address. | |
This function allocates an array of | num bytes and leaves it uninitialized. |
This function reallocates memory and expands it to | newsize. |
char name[100];
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char name[100]; char *description; strcpy(name, "Adam"); /* allocate memory dynamically */ description = malloc( 200 * sizeof(char) ); if( description == NULL ) { fprintf(stderr, "Error - unable to allocate required memory</p><p>"); } else { strcpy( description, "Adam a DPS student in class 10th"); } printf("Name = %s</p><p>", name ); printf("Description: %s</p><p>", description ); }
Name = Zara Ali Description: Zara ali a DPS student in class 10th
calloc(200, sizeof(char));
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char name[100]; char *description; strcpy(name, "Adam"); /* allocate memory dynamically */ description = malloc( 30 * sizeof(char) ); if( description == NULL ) { fprintf(stderr, "Error - unable to allocate required memory</p><p>"); } else { strcpy( description, "Adam a DPS student."); } /* suppose you want to store bigger description */ description = realloc( description, 100 * sizeof(char) ); if( description == NULL ) { fprintf(stderr, "Error - unable to allocate required memory</p><p>"); } else { strcat( description, "He is in class 10th"); } printf("Name = %s</p><p>", name ); printf("Description: %s</p><p>", description ); /* release memory using free() function */ free(description); }
Name = Adam Description: Adam a DPS student.He is in class 10th
The above is the detailed content of Dynamic Memory Allocation is a mechanism in the C language. It allows programs to dynamically allocate and free memory space at runtime. By using dynamic memory allocation, a program can dynamically allocate memory as needed without having to determine the memory size at compile time. This allows programs to manage memory more flexibly and make efficient use of available system resources.. For more information, please follow other related articles on the PHP Chinese website!