typedef-ing an array

Tim Writer writer at me.utoronto.ca
Fri Jun 29 10:39:38 AEST 1990


In article <78633 at srcsip.UUCP> pclark at SRC.Honeywell.COM (Peter Clark) writes:

>typedef char foo[29];
>foo bar = "Hello World, this is my test";

>void
>  main()
>{
>  bar = "Silly old me";
>  printf("%s\n",bar);
>}

>The initializer works fine, but the assignment inside main() doesn't.

You are forgetting the difference between an array and a pointer.  To quote
from K&RII (p. 99), "a pointer is a variable .... But an array name is not."
Therefore, you cannot assign an array, "Silly old me", to bar.  If `bar' were
a pointer, the compiler would simply assign the address of the first
character, `S' to `bar'.  But, `bar' is not a pointer.  Your compiler should
give a syntax error, something like `illegal lhs of assignment operator.'

To prove this to yourself, try this.

char	foo[29]="Hello world";

main()
{
	printf("%s\n",foo);
	foo="Goodbye world";
	printf("%s\n",foo);
}

If this does not generate a syntax error, your compiler is buggy.

Now try this.

typedef char	foo[29];

foo	bar="Hello world";

main()
{
	printf("%s\n",bar);
	strcpy(foo,"Goodbye world");
	printf("%s\n",bar);
}

Tim




More information about the Comp.lang.c mailing list