Last active
November 26, 2022 02:25
-
-
Save joegasewicz/03fbfaa795b1351d3ddac3d62f81a960 to your computer and use it in GitHub Desktop.
Dynamic Memory Allocation in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
int main() | |
{ | |
/* ====================================================================== */ | |
/* Dynamic Memory Allocation */ | |
/* ====================================================================== */ | |
char *str = NULL; | |
/* Initial memory allocation */ | |
str = (char*)malloc(4 * sizeof(char)); | |
strcpy(str, "joe"); | |
printf("String = %s, Address = %u\n", str, str); | |
/* Reallocating memory */ | |
str = (char*)realloc(str, 4 * sizeof(char)); | |
strcat(str, ".com"); | |
printf("String = %s, Address = %u\n", str, str); | |
free(str); | |
char *msg = NULL; | |
int limit = 0; | |
printf("Enter the limit:"); | |
scanf("%d", &limit); | |
msg = (char *)malloc(limit * sizeof(char)); | |
if (!msg) | |
{ | |
return -1; | |
} | |
printf("Enter the string:"); | |
scanf(" "); | |
gets(msg); | |
printf("result = %s\n", msg); | |
free(msg); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment