Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Quick query about (surprise!) pointers (http://www.go4expert.com/forums/quick-query-surprise-pointers-t5532/)

Tsukatu 30Jul2007 04:54

Quick query about (surprise!) pointers
 
I realize this may have been answered thousands of times already, but after some quick searching through archives I was unable to find the answer I was looking for.

I'm reading through a "Teach Yourself C in 21 Days" book (published '97), basically so I have a comprehensive learning experience in learning C++ and C#.
It says, and I quote:
Quote:

*string and string[] are equivalent
And later on it has two questions:
Quote:

Is this functional:
char *string1;
char *string2 = "this is a string";
string1 = string2;
...and the answer key says that it's perfectly fine.
The very next question is:
Quote:

Is this functional:
char string1[];
char string2[];
string1 = string2;
...and the answer key says that this will make your computer explode like a hand grenade (though not quite in those words).

So, if the question isn't obvious...
Is *string1 really == string1[], or is the book lying to me?
In both declarations ('char *string1' vs 'char string1[]'), 'string1 == &string1[0]' regardless, right? ...right?
So how are they different?

I feel like I'm taking crazy pills...

Thanks!

DaWei 30Jul2007 07:27

Re: Quick query about (surprise!) pointers
 
You cannot declare an empty array. You may declare what LOOKS like an empty array, if you initialize it, as in

char string [] = "This is a string";

That's a favor to you, from the compiler; the compiler can count the number of element that will be required.

*string and string [] are equivalent and either may be used as an argument to a function. A pointer to an array and the name of the array are equivalent, but not the same. The standard requires that there be a means of converting from an array name to a pointer to the first element of that array. If you use an array name and if you use a pointer to an array, then examine the emitted machine code, you will see that there is one level of indirection difference. The compiler has provided that for you, pursuant to the requirements of the standard.

I would suggest that you read the pointer tutorial referenced in my signature. It touches on that equivalency, but non-equality.


All times are GMT +5.5. The time now is 21:49.