Re: Simple question on Pointers
- From: "Alan Carre" <alan@xxxxxxxxxxxxxxxxx>
- Date: Tue, 25 Nov 2008 06:44:03 +0700
"Robby" <Robby@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote in message
news:C1962AB0-0055-42E0-B8C8-964B666C7462@xxxxxxxxxxxxxxxx
In a similar set up, if I do:
===============
int main()
{
char a[] = "hello world";
char **ap = &a;
return 0;
}
===============
Why does the latter example give the following warning?
c:\dts_visual_c++\misc_c_samples\misc_c_samples\utility.c(10) : warning
C4047: 'initializing' : 'char **' differs in levels of indirection from
'char
(*)[12]'
I know others have responded, but I'm not sure if they've made it perfectly
clear... and re-reading this just now I think I will not be much help
either!
Though you may find it amusing at least to consider the following:
--------------------
It is in fact not entirely incorrect to think of &a as being a char**. After
all, 'a' is a kind-of pointer or address to some characters. Just try
writing this down:
char a[] = "hello world";
char* pc = a;
No compile warnings. So a is a char* right? WRONG!
Well, sticking to 32 bit pointers, we can cast &a to char** (pointer to
char*), and it WILL work (by coincidence really). I say it will, and it does
work, strangely, "provided that we do not attempt to reference 'a' "!
Why? Well, certainly the address of a (&a) is a "pointer type" like any
address, but 'a' itself is not a pointer, it is a "reference". What that
means is that 'a' merely "represents", or "is an alias for" a memory address
where a char* is located (with data {"hello world\0"}). But the address
where 'a' is located is does not exist. Ok well, it does exists in a sense,
but it's more like a "dummy label" at best (and moreover, it is never used).
For instance try compiling this:
char a[] = "hello world";
char c = (&a+1)[0][0];
warning C4700: uninitialized local variable 'a' used
What do you mean "uninitialized???" I said a[] = "hello world"; !
That's right, 'a' is not initialized, 'a[]' is initialized though.
So we can certainly write down char c = (&a)[0][0] but only because we're
extracting *(&(a[0])) and:
a[0], a[1], .... a[12] are all initialized variables (12 variables). 'a',
however, is not.
- Alan Carre
.
- Follow-Ups:
- Re: Simple question on Pointers
- From: Doug Harrison [MVP]
- Re: Simple question on Pointers
- From: Cezary H. Noweta
- Re: Simple question on Pointers
- References:
- Simple question on Pointers
- From: Robby
- Simple question on Pointers
- Prev by Date: Re: clistctrl question
- Next by Date: Re: Two questions about using shared_ptr
- Previous by thread: Re: Simple question on Pointers
- Next by thread: Re: Simple question on Pointers
- Index(es):
Relevant Pages
|
Loading