Bonkers

muppet scott at asofyet.org
Sat May 12 17:40:58 BST 2007


On May 11, 2007, at 7:58 AM, Jon Nangle wrote:

> On Fri, May 11, 2007 at 12:37:57PM +0100, Peter Corlett wrote:
>
>> By value rather than by reference. It's fairly rare in C, but  
>> common enough
>> in C++.
>
> What's the syntax to pass an array by value in C? I can't see any  
> way to
> do it.

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

------------ snip -------------
#include <stdio.h>

/* traditional */
void
take_string_by_reference (char * string)
{
	strcpy (string, "fleeble");
	printf ("%s: string is now %s\n", __func__, string);
	printf ("    sizeof(string) = %d\n", sizeof (string));
}

/* doesn't actually work! */
void
take_string_by_value_try (char string[16])
{
	strcpy (string, "d'oh!");
	printf ("%s: string is now %s\n", __func__, string);
	printf ("    sizeof(string) = %d\n", sizeof (string));
}

/* wrap it in a struct */

struct string {
	char string[16];
};

void
take_string_by_struct_value (struct string string)
{
	/* changing stack copy, not original */
	strcpy (string.string, "fnord");
	printf ("%s: string is now %s\n", __func__, string.string);
	printf ("    sizeof(string) = %d\n", sizeof (string));
}

int
main (int argc,
       char *argv[])
{
	struct string string = { "this is a test" };

	printf ("%s: string is %s\n", __func__, string.string);

	take_string_by_value_try (string.string);

	printf ("%s: string is %s\n", __func__, string.string);

	take_string_by_reference (string.string);

	printf ("%s: string is %s\n", __func__, string.string);

	take_string_by_struct_value (string);

	printf ("%s: string is %s\n", __func__, string.string);

	return 0;
}

------------ snip -------------

Prints this:

------------ snip --------------
:w arytest.c
:!cc arytest.c -o arytest
:!./arytest
main: string is this is a test
take_string_by_value_try: string is now d'oh!
     sizeof(string) = 4
main: string is d'oh!
take_string_by_reference: string is now fleeble
     sizeof(string) = 4
main: string is fleeble
take_string_by_struct_value: string is now fnord
     sizeof(string) = 16
main: string is fleeble


------------ snip --------------

Only the last one passes the array by value, but not, er, passing an  
array.  Notice that even if you put a size on the arg in the  
prototype, it's still only a pointer.  The size merely tells the  
compiler how to write the offset math, and what kind of complaints to  
make about argument type mismatches.

--
It's all very complicated and would take a scientist to explain it.
   -- MST3K




More information about the london.pm mailing list