Bonkers

Andy Wardley abw at wardley.org
Sun May 13 09:35:22 BST 2007


muppet wrote:
> The only real way to pass an array by value is to wrap it up in 
> something else that you pass by value. 

I think you're missing the obvious.

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");
}

int
main (int argc, char *argv[])
{
     char *str = (char *) malloc(10);
     strcpy(str, "original");
     take_string_by_ref(&str);
     printf ("string is %s\n", str);
     return 0;
}

It's also worth noting that this is Not Allowed:

    char *string = "this is a test",
    strcpy(*string, "new string");

You shouldn't update static strings lest you crave a Bus Error
or Segmentation Fault.  Although your compiler may let you get
away with it, you really shouldn't do it.

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");

Caveat: I am not a C programmer (well, not that often)

A


More information about the london.pm mailing list