Modifying 2D char array passed to a function in C -
lacking money atm i'm offering $0.25 via paypal first person point out did wrong in code snippet -- hope doesn't violate site rules or insult anybody.
i want modify multi-dimensional array in function. gets modified while in function, when scope returns main function array unchanged.
the function headers cannot modified. helping me out.
void getalignment(char*s1, char*s2, char*s3, char*aligned[]) { /*********************** code here assigns char**tmp "different" "words" ***********************/ printf("tmp in getalignment function\n"); printf("%s %s\n", tmp[0], tmp[1]); // prints "different words", expected aligned = tmp; } int main(void) { // skipped code char** aligned = (char**)malloc(sizeof(char*)*2); aligned[0] = "should"; aligned[1] = "change"; printf("%s %s\n", aligned[0], aligned[1]); // prints "should change", expected getalignment(s1, s2, transcript, aligned); // how change aligned during call? printf("%s %s\n", aligned[0], aligned[1]); // prints "should change" return 0; }
when write inside getalignment:
aligned = (char**) malloc(2*sizeof(char*)); you making pointer getalignment::aligned point new memory. no longer points memory main::aligned points to. when operate on new memory, has no effect on memory main::aligned , pointing to.
(note - :: not c syntax, meaning disambiguate 2 variables both called aligned in local scope, despite fact 2 separate variables).
if intent code in getalignmentmodifies memory being pointed main::aligned remove above line.
if intent getalignment able allocate new memory, , main::aligned switched use new memory, have pass main::aligned reference (i.e. add level of indirection in function call). , don't forget free() previously-allocated memory.
btw don't cast malloc.
Comments
Post a Comment