|
From: Nicolas R. <ni...@bo...> - 2004-05-28 14:37:40
|
Hello Noorez,
> I have asked questions about pointers and arrays but all the answers=20=
> are not that great. Maybe I was unclear so I will explain my questions=20=
> better...
Thank you for the compliments. For great answers, I'd suggest (for the=20=
second time) that you google for some tutorials and reference. For even=20=
better answers, you can try reading the K&R ("The C Programming=20
Language) and/or Stroustroup's book ("The C++ Programming Language").
> int nArray[5]=3D{1,2,3,4,5};
> cout << nArray << endl;/*this gives the address of the array*/
Correct, because the name of an array of T is always a T* (a pointer to=20=
T). All arrays are pointers (implicitly).
> char sArray[6]=3D{'h','e','l','l','o',\0};
> cout << sArray << endl;/*this give the string hello, but i used the=20=
> name of the array without subscripts? Don't i get the address of it=20=
> like in the int array?*/
No, you get the string instead of the address because, as I told you=20
before, arrays of char get treated in a special way (due to the fact=20
that, in plain old C, they were the only way to represent strings of=20
characters). If you really want the address, you could cast the pointer=20=
to some other type first. If you don't know what 'to cast' means,=20
please look it up in TFM.
Again, as Per already said,
> cout always assumes that a pointer to a char is not just a pointer to=20=
> a single character but actually a pointer to the first character of a=20=
> zero-terminated string
Next question:
> char* pszString =3D "hello";/*strangest of all*/
> /*this looks as if you were trying to put "hello" where the address=20=
> of a char would go.*/
The easy way to think about this is the one I already said: C/C++=20
provide special syntax to assign constant strings into arrays of char.=20=
(It would be rather unpractical if they didn't.)
What's going on behind the scenes there is that the string "hello" gets=20=
created "on the fly" by the compiler as a constant array of chars that=20=
contains {'h', 'e', 'l', 'l', 'o', \0}. Then you create a=20
pointer-to-char called pszString. What does the assignment do? It just=20=
copies the address. So pszString now points to the same place where the=20=
compiler stored the array containing the constant string.
Good luck with your C/C++ learning. You will encounter many, many such=20=
quirks along the way. Please try to use the excellent and free FAQs and=20=
tutorials around. They are your friends.
Regards,
Nicol=E1s
|