i'm relearning c @ moment , wrote small piece of test code while reviewing pass reference:
#include <stdio.h> #include <string.h> void distort_flags_list(char*** flags); int num_flags = 2; int main(int argc, char** argv) { distort_flags_list(&argv); (int flag_offset = 0; flag_offset < num_flags; flag_offset++) { printf("%s\n", *(argv + flag_offset)); } return 0; } void distort_flags_list(char*** flags) { char* tester[2] = {"first", "second"}; *flags = tester; } i'm curious why when running this, following output:
first (null) rather printing "first" , "second". understanding when passing pointer argv distort_flags_list, you're changing place pointer points address of tester defined within function.
any explanation why happens?
in function distort_flags_list, setting value of *flags value not valid once function returns.
accessing argv after call distort_flags_list undefined behavior.
to make sure value *flags continues valid after function returns, you'll need use dynamic memory allocation.
void distort_flags_list(char*** flags) { *flags = malloc(2*sizeof(**flags)); (*flags)[0] = malloc(20); // make large enough (*flags)[1] = malloc(20); // ditto strcpy((*flags)[0], "first"); strcpy((*flags)[1], "second"); } and then, add code deallocate memory in main.
int main(int argc, char** argv) { distort_flags_list(&argv); (int flag_offset = 0; flag_offset < num_flags; flag_offset++) { printf("%s\n", *(argv + flag_offset)); } free(argv[1]); free(argv[0]); free(argv); return 0; }
Comments
Post a Comment