On Dec 11, 6:52 am, Lin...@gmail.co m wrote:
I find strange result in the following program.
1. For string array, dereferencing it will result in the string
itself, but for int array, dereferencing it will result in the address
of the array;
2. When dereferencing it twice (operator **), why the result is always
the 1st element in both string array sample and int array sample?
-
#include <iostream>
-
#include <string>
-
-
-
using namespace std;
-
-
-
-
-
int main()
-
{
-
wchar_t me[] = L"Hello World \n";
-
-
-
Here's probably part of your misunderstanding. This isn't a
-
string array, but rather an array of characters (wchar_t).
-
-
-
wchar_t (*me2_ptr)[14] = &me;
-
wcout << *me2_ptr << endl; // output Hello World
-
wcout << **me2_ptr << endl; // output H
-
-
-
-
-
int values[] = { 10, 20, 30, 40, 55, 60, 70, 80, 90, 100 };
-
int (*pval)[10] = &values;
-
wcout << *pval << endl; // output 0x0017f6f0
-
wcout << **pval << endl; // output 10
-
-
-
-
-
return 0;
-
}
-
-
-
ostreams don't support output of an array. On the other hand,
array's do convert implicitly to pointers, and ostreams do
support output of pointers. In the case of pointers to
character types, there is a special overload, which allows them
to treat the pointer as the beginning of a C style string;
there's nothing similar for pointers to int, so you just output
the pointer.
As for dereferencing twice: that's just the way C (and thus C++)
works. Arrays are second class citizens in C: formally, there
is no indexing, but rather pointer arithmetic and
dereferencing---the expression "a[i]" is defined to be "*(a+i)".
And of course, *a is the same thing as *(a+0).
Because of such anomalies, it's better to avoid C style arrays
(and strings) as much as possible: just use std::wstring and
std::vector, and things will behave rationally.
--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34