1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
char* copy_string_to_heap(char* s) {
int num_bytes = 0;
while(s[num_bytes] != '\0') {
num_bytes += sizeof *s;
}
num_bytes += sizeof *s; // for null terminator '\0'
char* s_on_heap = malloc(num_bytes * sizeof *s_on_heap);
for(int i = 0; i < num_bytes; i++) {
s_on_heap[i] = s[i];
}
return s_on_heap;
// BENEFIT of malloc(…): Heap memory does not go away (i.e., deallocated/freed)
// when function returns, so the array (string) contents
// will still be there for main(…).
}
int main(int argc, char* argv[]) {
char s_orig[] = "ABCDEF";
char* s_copy = copy_string_to_heap(s_orig);
printf("s_orig == %s\n", s_orig);
printf("s_copy == %s\n", s_copy);
free(s_copy);
s_copy = NULL;
return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2024 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.