Not familiar with C, please correct me on any mistakes.
here’s some code:
void db_cstr(char* cstr, int len) {
char* temp2 = cstr;
cstr = (char*)malloc(len*2*sizeof(char));
// print 1
printf(cstr);
printf("\n");
//print 2
printf(temp2);
printf("\n");
strcpy(cstr, temp2);
//free
free(temp2);
//print 3
printf(cstr);
}
int somefunction(){
int array_len = 10;
char* cmd = (char*)malloc(array_len*sizeof(char));
strcpy(cmd, "apple");
db_cstr(cmd, array_len);
// final print
printf(cmd);
return 1;
}
My values(always) for // print 1 == “” and // print 2 == “apple” and // print 3 == “apple”. However, when I do final print, printf prints nothing. I assumed this had to do with free(temp2); so when I commented it out the final print was “apple”. I believe this is because the orignal cmd pointer in somefunction is still pointing to the freed array at temp2. How do you make the cmd pointer point to what the new cstr is pointing to in db_cstr. (I don’t want db_cstr to return anything).
If you want a function to change a var, you should pass a pointer to it. This is true even when the var is a pointer.
so:
void db_cstr(char** cstr, int len),db_cstr(&cmd, array_len);, and so on…by the way, don’t use printf directly on a var. use
printf("%s",cmd)instead.