Re: regarding * and ++ operators
- From: "Malcolm" <regniztar@xxxxxxxxxxxxxx>
- Date: Sun, 17 Dec 2006 22:40:00 -0000
<sam_cit@xxxxxxxxxxx> wrote in message news
Hi Everyone,The first area of confusion.
I often get confused with * and ++ operator when they are used with
pointers as to which would be considered first by the compiler, Can
anyone explain with some examples to understand them easier???
char *ptr;
declares ptr as a pointer to data of type char.
*ptr = 'a';
dereferences ptr. Or in other words, puts the character 'a' in the place
pointed to by ptr.
Note that, as the code stands, ptr is uninitialised. To have a working,
though useless function we need
void foo(void)
{
char ch;
char *ptr = &ch;
&ptr = 'a';
}
It is comparatively rare for pointers to point to sinle objects. After all,
normally you would just use ch itself.
They come into their own with arrays.
char buff[1024];
char *ptr = buff;
sets ptr to point to the first entry in buff
now let's say we want a function that will set a string to all 'a', adding a
terminating null.
void allas(char *str, int N)
{
int i;
for(i=0;i<N;i++)
*ptr++ = 'a';
*ptr = 0;
}
see how compact and expressive this notation is. The ++ is more binding than
the derefernece, but it is applied last. This is a reversal of normal rules
of mathematical notation, but is is extremely convenient. You very
frequently want to use a pointer to step through an array.
--
www.personal.leeds.ac.uk/~bgy1mm
freeware games to download.
.
- Follow-Ups:
- Re: regarding * and ++ operators
- From: August Karlstrom
- Re: regarding * and ++ operators
- From: Richard Heathfield
- Re: regarding * and ++ operators
- From: Robert Gamble
- Re: regarding * and ++ operators
- References:
- regarding * and ++ operators
- From: sam_cit
- regarding * and ++ operators
- Prev by Date: Re: How does C handle issues arising out of Endianness?
- Next by Date: Re: does a program work in all cases?
- Previous by thread: regarding * and ++ operators
- Next by thread: Re: regarding * and ++ operators
- Index(es):
Relevant Pages
|