+ 1
Please explain arrays and pointers in detail ????
how do they relate and examples !!!
1 Respuesta
+ 2
Pointers point to a location in memory.
Let's take a variable x:
int x = 10;
x is stored somewhere in memory, to get it's location we can use &x. Let's make a pointer p that points at x:
int* p = &x; /* int* means we have a pointer that points at an integer, we want the pointer to point to x so we give it the position of x with &x */
To access the value of x with p we can use *p. If we change x the value of *p will also change and vise versa.
*p = 20 /* now x is 20 */
If you declare an array, let's call it test (int test[5];) you basically get a pointer named test that points to the first element in the array.
Writing *test is the same as using test[0].
To access the second element of the array you can either use test[1] or *(test+1)
If you want the pointer to the second element you can either use test+1 directly or &test[1]
This all might look quite complicated right now, try to write a few small programs with pointers so you really understand what's going on.