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 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
// { "hello", "world" }
bool create_string(char** a_result) {
// note: we want sizeof(char), so dereference twice
*a_result = malloc(sizeof(**a_result) * 4);
(*a_result)[0] = 'a';
(*a_result)[1] = 'b';
// pitfall: order of operations can cause trouble
// *(a_result[i]) != (*a_result)[i]
// C interprets *a_result[i] as the left
(*a_result)[2] = 'c';
(*a_result)[3] = '\0';
return true;
}
int main(int argc, char* argv[]) {
char* result; // unititalized
bool is_success = create_string(&result);
printf("success: %d, result: %s\n", is_success, result);
return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2022 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.