Pointers and arrays

Can someone explain the reason for pointers. i have setup an array like the following.

int* a = NULL;
int n;
cin >> n;
a = new int[n];

This will setup my array size based on the number that a person enters. If I want to load this array with numbers or if the array was a character array, what will pointers do for me?
'a' is a pointer.
'a' is in fact a pointer, thank you for pointing that out, helios.

Declaring an int *a is essentially the same thing as declaring an array of integers. read http://cplusplus.com/doc/tutorial/pointers/ for more information on pointers.

The reason you need a pointer in this situation is because if you did this
1
2
3
int x;
cin >> x;
int a[x];

you would get a compiler error.

after what you've done already, you can use your array like
1
2
3
4
a[0] = 20;
a[1] = 5;

cout << a[0] << endl; // etc.  
Last edited on
Declaring an int *a is essentially the same thing as declaring an array of integers


Ehhhhhh
It's not exactly the same thing... But somewhat the same. Rather, the functionality can be the same.
What is the difference then between allocating an array as:
nt* a = NULL;
int n;
cin >> n;
a = new int[n];

and allocating an array as int a[20];
so if I use pointer in assigning the array and I have a user input 25 different numbers into the array, will the array hold the address of those numbers or the actual numbers?
What is the difference then between ...


int a[20]; Gives you an array of exactly 20 ints. No more, no less.

int a* = new int[n]; Gives you an array of 'n' ints. This is useful if the value of 'n' is not known at compile time (like if you get it from a file, or from the user)

so if I use pointer in assigning the array and I have a user input 25 different numbers into the array, will the array hold the address of those numbers or the actual numbers?


it will hold the actual numbers.
Topic archived. No new replies allowed.