// more pointers
#include <iostream>
usingnamespace std;
int main ()
{
int numbers[5]; // Declare an array of 5 integers
int * p; // Declare a pointer
p = numbers; // makes our pointer 'p' point to the first entry in the 'numbers' array.
// that is.. it points to numbers[0].
// using an array name without [brackets] like this is shorthand for a pointer
// to the first element. This statement is the same as:
// p = &numbers[0]
*p = 10; // assigns 10 to whatever p points to. Since p points to numbers[0],
// this effectively assigns numbers[0]. IE: same as doing:
// numbers[0] = 10;
p++; // This increments the pointer so it points to the next integer in memory
// which would be the next element in the array. So now, p points to
// numbers[1]
*p = 20; // Assigns 20 to whatever p points to (numbers[1])
p = &numbers[2]; // Makes p point to numbers[2]
*p = 30; // Assigns 30 to whatever p points to (numbers[2])
p = numbers + 3; // Takes a pointer to the first element in the array (numbers[0] .. same shorthand
// we saw above), and adds 3 elements to it to get a pointer to the [3] element.
// then assigns that to p. So now p points to numbers[3]
*p = 40; // Assigns 40 to whatever p points to (numbers[3])
p = numbers; // Resets p so it points back to numbers[0]
*(p+4) = 50; // This takes the pointer stored in p (&numbers[0]), adds 4 elements to it
// (giving us &numbers[4]), then assigns 50 to whatever that result points to
// since that result points to numbers[4], this assigns 50 to numbers[4]
for (int n=0; n<5; n++)
cout << numbers[n] << ", "; // prints all entries of numbers, which should result in:
// 10, 20, 30, 40, 50
return 0;
}
a[5] = 0; // a [offset of 5] = 0
*(a+5) = 0; // pointed by (a+5) = 0
Both mean the same thing ;
1 2 3 4 5 6 7 8 9 10 11 12
int a[5];
int *b = newint[5];
//Both are the same except variable a will be automatically deallocated whereas b needs to manually deallocated
a[0] = 1;
a[1] = 2;
//or can also be done as
//*(a+0) = 1; // points to *a
//*(a+1) = 2; // points to the next block of 4 bytes after *a;
//Oh and not to forget this
std::cout << "a[0] = " << *(a+0) << std::endl; //Prints 1;
std::cout << "a[1] = " << *(a+1) << std::endl; //Prints 2;
delete b;