c - Can someone review this exercise? I was right, but want to clarify a few things -
1 void myfunc(char** param){ 2 ++param; } int main(){ 3 char* string = (char*)malloc(64); 4 strcpy(string, "hello_world"); 5 myfunc(&string); 6 myfunc(&string); 7 printf("%s\n", string); // ignore memory leak sake of quiz 8 homecoming 0; }
what should programme print? a) hello_world b) ello_world c) llo_world d) lo_world e) illegal memory access, undefined behavior
my dissection, line line. please proofread, started learning c few weeks ago , pointers/memory management starting "click" in brain!
declares function of type void called 'myfunc' 1 parameter: ptr ptr char array 'param' defines 'myfunc': returns argument 'param' prefixed increment defines ptr character array 'string', allocates 64 bytes of memory 'string' ptr assigns string "hello_world" 'string' calls 'myfunc', passes address of 'string' argument, increments/shifts address 1 byte up(?). same line 4, address 2 bytes away answer- it's trick question; although address of 'string' manipulated, printf function passed actual string, not pointer. therefore, output simply: hello_worldnow, couple questions. how 1 alter code b), c), d), or e) right answer? also, memory leak they're talking due fact there 2 "unfreed" bytes of memory after null character, because pointer shifter on 2 bytes? if not, mean?
the function
void myfunc(char** param){ ++param; } doesn't expect to. modifies param locally , has no effect on value of &string in calling function. need use:
void myfunc(char** param){ ++(*param); } if want alter string points in main.
c pointers memory sample strcpy
No comments:
Post a Comment