Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An example of how you can use malloc(), realloc(), and free() to create dynamic strings.
#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
You can’t perform that action at this time.