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 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include <string.h>
// Okay to copy/adapt for homework -- but probably not directly applicable
//
char* copy_string_to_heap(char const* s) {
return strcpy( malloc(strlen(s) * sizeof *s), s );
}
int main(int argc, char* argv[]) {
char* strings_stack[] = { copy_string_to_heap("AB"),
copy_string_to_heap("CD"),
copy_string_to_heap("EF"),
copy_string_to_heap("GH"),
copy_string_to_heap("IJ") };
size_t num_strings = sizeof strings_stack / sizeof strings_stack[0];
char** strings_heap = malloc(num_strings * sizeof *strings_heap);
for(int i = 0; i < num_strings; i++) {
char* s = strings_stack[i];
strings_heap[i] = s;
}
for(int i = 0; i < num_strings; i++) {
printf("strings_heap[i] == \"%s\"\n", strings_heap[i]);
}
// TODO: free memory
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.