Bonkers

muppet scott at asofyet.org
Sun May 13 15:38:29 BST 2007


Andy Wardley wrote:
> 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 '*'.

If you do that with an array in C you are passing a pointer to a pointer. 
This is quite handy when you need to realloc() an array, but does not really
apply to the question of how to pass an entire array on the stack (which is
the practical C meaning of "by value").


> 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.

My compiler won't let me get away with that, because string is a char*, and
*(char*) is a char, and strcpy() wants a char*, not a char, so of course that
is Not Allowed!  ;-)

But, i think you misread the original, because...


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

That says "on the stack, have a pointer, and in that pointer store the address
of some memory on the heap."

On the other hand, i could say

    char string[] = "something";

and the compiler will allocate enough space for "something\0" on the stack,
copy those bytes into, and use "string" as a pointer to the first byte, every
time i enter the function.  It's on my stack so i can write to it all i want
--- but i can't realloc() it and shouldn't write off the end.  In effect,
that's what my original code was doing with the struct in main().


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

:-)

These issues are all why we like perl so much.  I mean, when have you ever had
to deal with this stuff in perl?  Except, maybe, when some well-meaning intern
goes through "that nasty, ugly perl code" and changes all the direct
references to @_ to lexicals, and then wonders why the changes made in the sub
are no longer reflected in the caller...


-- 
muppet <scott at asofyet dot org>



More information about the london.pm mailing list