Created
April 24, 2019 15:50
-
-
Save jesselawson/681c804bbde0eb988bebe6a7015bcbda to your computer and use it in GitHub Desktop.
An example of how you can use malloc(), realloc(), and free() to create dynamic strings.
This file contains 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 <string.h> | |
#include <stdlib.h> | |
int main(void) { | |
// sizeof(char) is always 1, but we have it here | |
// for instructional purposes | |
char* full_name = malloc(sizeof(char)*strlen("Jesse Lawson")+1); | |
strcpy(full_name, "Jesse Lawson"); | |
printf("Old value of full_name:\n"); | |
for(int i=0; i<strlen(full_name); i++) { | |
printf("[%d] %c\n", i, full_name[i]); | |
} | |
// Now we will realloc the space | |
full_name = realloc(full_name, sizeof(char)*strlen("Jesse Happy Bubble Fun Club Lawson")+1); | |
strcpy(full_name, "Jesse Happy Bubble Fun Club Lawson"); | |
printf("New value of full_name:\n"); | |
for(int i=0; i<strlen(full_name); i++) { | |
printf("[%d] %c\n", i, full_name[i]); | |
} | |
free(full_name); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment