All about Pointers
I am sure it will help a lot of students
Member • Jan 16, 2011
Member • Jan 20, 2011
Administrator • Jan 20, 2011
Member • Jan 20, 2011
void main()
{
int a[5]; //creating an integer array to store upto 5 integers
cout<<a; //output is the memory address of the element a[0] ie starting address of array
//one way to access elements of array
for(int i=0;i<5;i++)
cout<<a[i];
//another way using pointers
for(int i=0;i<5;i++)
cout<<*(a+i); //*(a+i) is equivalent to a[i]
}
This was the case of static sized arrays ie size of the array is known at the compile time. //this is okay const int size=5; //creating a constant variable int a[size]; //but this is wrong int size=5; int a[size];so to create dynamic arrays (eg when size has to be known from the user), we make use of pointers as-->
int size; int *a; //uninitialized pointer cout<<"Enter the size of the array: "; cin>>size; //got the array size from the user a=new int[size]; //a can now hold upto 'size' number of variables //now the elements of 'a' can be accessed in any of the 2 ways discussed above.Also there is a difference between int a=new int[size]; and int a=new int(size);