|
From: Daniel K. O. <dan...@ya...> - 2005-08-12 12:10:00
|
Farzan Hajian wrote:
> I have a problem with variable declaration.
> Please tell me what the following declaration means?
>
> int * const * ptr;
>
> I know that "ptr" is a pointer to "int * const". But what "int *
> const" means.
I know that Shachar already answered, but I thought that it was a bit
confusing; so I'll try too.
Considering that T is a type, you can write:
T obj;
T * pobj;
Where "obj" is a variable of type "T", and "pobj" is a pointer to a
variable of type T.
Now, replace "T" with a type like "int" and you have:
int obj;
int * obj;
But "int *" is also a type; you could write:
typedef int * pint; /* now "pint" is a synonym for "int *" */
pint obj;
pint * pobj;
The typedef "pint" is just a convenience here; if you remove it, you can
write the equivalent code:
int * obj;
int * * pobj;
So, "obj" is a pointer to "int", and "pobj" is a pointer to pointer to
"int".
Now if you want to declare the "int" value as constant, you can:
const int * * pobj;
or
int const * * pobj;
Now you can't change the end of the two pointers (the "int" value).
int * a;
pobj = &a; /* ok, assigning the address of variable "a" */
*pobj = a; /* ok, assigning the address stored in "a" */
**pobj = *a; /* error, assignment of read-only location */
You can also declare the variable itself ("pobj") as const, so its value
can't be changed.
int * a;
int * * const pobj;
pobj = &a; /* error, assignment of read-only location */
*pobj = a; /* ok, assigning the address stored in "a" */
**pobj = *a; /* ok, assigning the integer pointed by "a" */
And finally, you can add a const so the value pointed by "pobj" (a
pointer) can't be changed.
int * a;
int * const * pobj;
pobj = &a; /* ok, assigning the address of variable "a" */
*pobj = a; /* error, assignment of read-only location */
**pobj = *a; /* ok, assigning the integer pointed by "a" */
---
Daniel K. O.
_______________________________________________________
Yahoo! Acesso Grátis - Internet rápida e grátis.
Instale o discador agora! http://br.acesso.yahoo.com/
|