Skip to content

Instantly share code, notes, and snippets.

@jesselawson
Created April 24, 2019 15:50
Show Gist options
  • Save jesselawson/681c804bbde0eb988bebe6a7015bcbda to your computer and use it in GitHub Desktop.
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.
#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