ssai ssai - 1 month ago 21
C Question

[] pointers operations in c

int x[4] = {12, 20, 39, 43}, *y; y = x; Assume each expression is evaluated after the previous one (take all previous ones in consideration)
*y + 1
*(y + 1) y += 2;
*y = 38
*y - 1
*y++
*y
y[0] [Hint: y is not pointing to x[0] anymore so think about it and search for what it means]


Here the question i'm trying to solve

1: what does y[0] means ?

I searched online and find nothing !

2:(*y-1) is the operation evaluated left to right ? is y going to point on the element before the one it points at it now?

thank you

Answer

A pointer is an address in memory.

If you have an int*, it is the address of an int.

Now you have two differents way to access to the value at this address.

int a = 1;
int *ptr = &a; // ptr is the address of a

printf("%d\n", *ptr); // should print "1" because *ptr is the content at the address stored in ptr

Now when we work with array, this syntax is not easy to to read, so there is another syntax which is:

int array[4] = { 21, 42, 84, 64 };
// Here array is also an address, the address of the first element

printf("%d\n", array[1]); // this should print "42"

In fact when you use the array syntax aka array[1], it is exactly as if you were doing *(array + 1).

It is also why the first element of an array is [0], because it's like if you were doing *(array + 0).

So when you have a pointer (or an array, it's the same), *ptr == ptr[0].

I will put every answer to your question with an example:

int x[4] = {12, 20, 39, 43}, *y;
y = x;
*y + 1; // 13
*(y + 1); // 20 (same as y[1])
y += 2; // y is now the address of 39
*y = 38; // { 38, 43 }
*y - 1; // 37
*y++; // 43 (y++ then *y)
*y; // 43
y[0]; // 43

The '*' operator applies on the whole block on his right. *y + 1 is like y[0] + 1 and *(y + 1) is like y[1]`

When you increment a pointer (by doing ptr += 2 or ptr++), the address is in fact incremented by the size of the element.

int y = 42;
int *ptr = &y;

ptr += 2; // ptr is now 8 bytes (2 * syzeof(int)) further &y

EDIT: If you want more details on the operator priorities, you can also look at this link. http://en.cppreference.com/w/c/language/operator_precedence

Comments