gcc not compiling

Derek Martin code at pizzashack.org
Mon Oct 31 21:01:03 UTC 2005


On Mon, Oct 31, 2005 at 01:30:44PM -0600, STYMA, ROBERT E (ROBERT) wrote:
> The syntax:
> int main(int argc, char **argv)
> works, but most of the C books I have seen recommend
> the *argv[] version.

I meant to comment that these two different notations are functionally
identical; an array name is nothing more than a pointer.  For example,
if we have the following code:


	#include <stdio.h>
	void main (void){
	
		char foo[] = "This is a string\n";
		char *bar = foo;
	
		/* these expressions all print "T\n" */
		printf("%c\n", foo[0]);
		printf("%c\n", *bar);
		printf("%c\n", bar[0]);
		printf("%c\n", *foo);
	
		/* these expressions all print "i\n" */
		printf("%c\n", foo[2]);
		printf("%c\n", *(bar + 2));
		printf("%c\n", bar[2]);
		printf("%c\n", *(foo + 2));
	}

The results may surprise programming students:

	$ gcc -o ptr ptr.c
	ptr.c: In function `main':
	ptr.c:2: warning: return type of 'main' is not `int'
	[ddm at archonis ~]
	$ ./ptr
	T
	T
	T
	T
	i
	i
	i
	i
	

In reality, foo[x] is just "syntactic sugar" for *(foo + x).  This
is called pointer math, and works properly regardless of the size and
type of foo, so long as it was declared properly before being used.

[I'm very bored today...]

-- 
Derek D. Martin
http://www.pizzashack.org/
GPG Key ID: 0x81CFE75D

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
URL: <http://listman.redhat.com/archives/fedora-list/attachments/20051031/bced3319/attachment-0001.sig>


More information about the fedora-list mailing list