Re: regarding * and ++ operators






<sam_cit@xxxxxxxxxxx> wrote in message news
Hi Everyone,

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???

The first area of confusion.

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.


.



Relevant Pages