Pointers to int
Hello,
Can anyone explain to the list how this pointers to int work:
int *p;
p = (int *)(array);
for (i = 0; i < arraysize - 1; i += 4)
*p++ = j - 8;
*p = 0x0;
P is defined as a pointer to a int. Then, it points to (the beginning ? ) a char array. What is the result of perform the instruction: *p++; ?
First, what is it? It adds 1 to what?
Thanks for a detailed explanation,
fabolo
Quoted 10 lines · Fabio Andres Miranda
Can anyone explain to the list how this pointers to int work:
int *p; p = (int *)(array); for (i = 0; i < arraysize - 1; i += 4) *p++ = j - 8; *p = 0x0;P is defined as a pointer to a int. Then, it points to (the beginning ? ) a char array.
What is the result of perform the instruction: *p++; ?
As postincrement (++) has higher priority than dereference (*), p++ is what will be evaluated first. So p will be incremented by the size of an integer (probably 4). After that, p will point to the second integer of the array, i. e. array[1]. Now you use * to access that very location and store j-8 there.
HTH,
Christoph
Signature · 4 lines
``There's no dark side of the moon, really Matter of fact, it's all dark'' --Pink Floyd
Quoted 5 lines · Christoph Bussenius
As postincrement (++) has higher priority than dereference (*), p++ is what will be evaluated first. So p will be incremented by the size of an integer (probably 4). After that, p will point to the second integer of the array, i. e. array[1]. Now you use * to access that very location and store j-8 there.
Sorry, I was mistaken. As the result of a POSTincrement is the value before incrementing, the result will be like:
*p = j-8;
p++;
Christoph
Signature · 4 lines
``There's no dark side of the moon, really Matter of fact, it's all dark'' --Pink Floyd
Quoted 9 lines · Fabio Andres Miranda
Can anyone explain to the list how this pointers to int work:
int *p; p = (int *)(array); for (i = 0; i < arraysize - 1; i += 4) *p++ = j - 8; *p = 0x0;P is defined as a pointer to a int. Then, it points to (the beginning ? ) a char array.
When used as an expression, an array variable evaluates to a pointer to its first element.
Quoted 1 line
What is the result of perform the instruction: *p++; ?
The expression "*p++ = j - 8" will store j-8 in the (int) location referenced by p, then increment p so it points to the next location (i.e. increments the address by sizeof(int)).
Quoted 1 line
First, what is it? It adds 1 to what?
It evaluates to the p, incrementing p as a side-effect.
It "adds 1" to p in the sense that p will point to the next int. Adding a value to a pointer scales the value by the size of the type being pointed to, e.g. if p has type "pointer to T" for some type T, then the expression:
p + n
is equivalent to:
(T*)((char*)p + n * sizeof(T))
Signature · 1 line
Glynn Clements <[email protected]>