Re: gcc not compiling

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Derek Martin wrote:
> 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:

Not true.  Or rather, only partially true.
In a variable declaration the two are *not* equivalent.  In a parameter
declaration and in an expression, the two *are* equivalent.
The difference is, in a variable declaration, you also specify how much
space is to be allocated for the variable, which is not the case for the
other uses.
So, the books are indeed correct, **argv and *argv[] are equivalent
*when used in the parameter list*.

> 
> 	#include <stdio.h>
> 	void main (void){
> 	
> 		char foo[] = "This is a string\n";

And this is totally different from
		char *foo = "This is a string\n";
The former declares an array and gives it a name, the latter declares an
anonymous array (string) and creates a pointer to it.  With the former
declaration, you cannot alter the value of foo, with the latter you can
(alter as in foo = some_other_value; or foo++;).

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


-- 
Sjoerd Mullender

Attachment: signature.asc
Description: OpenPGP digital signature


[Index of Archives]     [Current Fedora Users]     [Fedora Desktop]     [Fedora SELinux]     [Yosemite News]     [Yosemite Photos]     [KDE Users]     [Fedora Tools]     [Fedora Docs]

  Powered by Linux