char subject[]="Bonkers"

Andy Wardley abw at wardley.org
Sun May 13 17:39:10 BST 2007


Andy Armstrong wrote:
> That's just a double indirection - only useful if you want to change the 
> address pointed to rather than the contents of the address. 

Ah, sorry.  Yes, I went one level of indirection the wrong way.

Daniel Barlow wrote:
 > Mind you, the meaning of "pass by value" *does* vary widely depending on
 > exactly which religion you subscribe to ...

That's maybe where I went wrong.  I mis-parsed "pass by value" as meaning
"how do I pass a reference to the value I'm using here in the caller".
But looking back, it was clear that it didn't mean that at all.  My mistake.

muppet wrote:
 >>    char *string = "this is a test",
 >>    strcpy(*string, "new string");
 >
 > My compiler won't let me get away with that...

Ah shoot!  I'm having a really bad day :-)

I mistyped that.  The example in the code was correct:

 >      char *str = (char *) malloc(10);
 >      strpcy(str, "original");

muppet:
 > 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,

Yes, although I purposely avoided that in my original example because it
doesn't work with the double indirection.

#include "IANACP.h"

The compiler _will_ treat 'string' as a pointer to the first byte (that's the
"equivalence of arrays and pointers" that often confuses people, myself
included), _but_ that doesn't mean that char string[] is the same type as char
*string.  So when you take the address of it, &string is a pointer to an array
of char while the function was expecting char **, a pointer to a pointer to a
char.  GCC complains and the program segfaults.

Furthermore, if you were doing a realloc() kind of thing, then you would need
to use a pointer rather than an array (which can't be resized).  But that's
a moot point, because that's not what the original question was about, nor
what your answer was suggesting.  And all this is in the C FAQ which gives
much more reliable advice on C than me:

http://c-faq.com/aryptr/index.html

 > These issues are all why we like perl so much.

Totally!

By the way, I've totally lost track of how the thread started with Perl jobs
and ended up here.  Is this an interview question?  Did I get the job?

A



More information about the london.pm mailing list