Bonkers

Andy Armstrong andy at hexten.net
Sun May 13 13:01:28 BST 2007


On 13 May 2007, at 09:35, Andy Wardley wrote:
> You can pass a reference to a string/array using '&' and then
> de-reference it again at the other end with '*'.
>
> #include <stdio.h>
> #include <string.h>
> #include <stdlib.h>
>
> void
> take_string_by_ref (char **str)
> {
>     strcpy(*str, "changed");
> }

That's just a double indirection - only useful if you want to change  
the address pointed to rather than the contents of the address. It's  
unnecessary in this example.

void take_string(char *str) {
     strcpy(str, "changed");
}

works too.

> If you plan to monkey with the contents of a string then you
> should always allocate it on the heap using malloc.
>
>     char *str = (char *) malloc(10);
>     strpcy(str, "original");

Or indeed

char *str = strdup("original");

-- 
Andy Armstrong, hexten.net



More information about the london.pm mailing list