About 20 days ago, "John Harrison" <>
replied to a message which I had written:
> > > Q1 . What is the use of pointer to an array?
> >
> > It points to it. (The name of an array is also a pointer to it.)
>
> No, the name of an array decays to a pointer to the first element of the
> array. A pointer to an array and a pointer to the first element of an array
> are not the same thing.
>
> int a[10];
> cout << &a + 1 << endl;
> cout << a + 1 << endl;
>
> The two statements print different pointer values, proving that a pointer to
> an array (first case) and a pointer to the first element of an array (second
> case) are not the same.
I was dubious, so I wrote this program:
#include <iostream>
using std::cout;
using std::endl;
int main(void)
{
int a[10];
cout << "int a[10];" << endl;
cout << " &a : " << (&a) << endl;
cout << " a : " << ( a) << endl;
cout << "&a + 1 : " << (&a + 1) << endl;
cout << " a + 1 : " << ( a + 1) << endl;
return 0;
}
and I got these results:
wd=C:\C\test
%array-pointer-test
int a[10];
&a : 0x6cffac
a : 0x6cffac
&a + 1 : 0x6cffd4
a + 1 : 0x6cffb0
Interestingly, the value of &a and a are the same. But when incremented,
one increments 4 bytes, the other 40 bytes.
Of course. They're pointers to different types, one of size 4 and the other
of size 40. I should have known that. ::: kicks self :::
In C, however, depending on the context, the compiler is likely to
implicitly cast the pointer from pointer-to-array to pointer-to-int.
For example, consider the following code:
/* char-array-test.c */
#include <stdio.h>
char Func(char* blat)
{
return *(blat+1);
}
int main(void)
{
char a[80];
a[0] = 'n';
a[1] = 't';
printf("Func(&a) = %c\n", Func(&a));
return 88;
}
This prints 't' in C, but it won't even compile in C++.
I think I shouldn't have learned C before C++; I've picked up some bad
habits that way.
--
Cheers,
Robbie Hatley
Tustin, CA, USA
email: lonewolfintj at pacbell dot net
web: home dot pacbell dot net slant earnur slant
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---