Using pointer instead of array.

Hi.Just started using pointers. I'm trying to use them instead of arrays but i get this error after the program finishes: Run-Time Check Failure #2 - Stack around the variable 'q' was corrupted. Anyway here's the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;
int main ()
{int q=0,n,i,aux,j; int* p;
cout<<"Introduceti numarul de elemente:"; cin>>n;
p=&q;
for (i=1; i<=n; i++) cin>>*(p+i);
for (i=1; i<n; i++) for (j=i+1; j<=n; j++) if (*(p+i)>*(p+j)) {aux=*(p+i);
                                                               *(p+i)=*(p+j);
								*(p+j)=aux;}
for (i=1; i<=n; i++) cout<<*(p+i)<<" ";
return 0;
}
q is only a single int, so you can't use it like it's an array. Anyway, arrays and pointers behave exactly the same way:

p[1] == *(p+1) regardless of whether or not p is an "array" or a "pointer".
I'm trying to do this because with a pointer i can have an infinite number of spaces, also i use just as much memory as i need. With an array i got an error that its too long after trying to get more then 1010 spaces. Is there any way i can use a pointer this way?
if you cant make an array that big, and cant allocate that amount with new

Then try an array of pointers if theres no other way

1
2
3
int** array = new int*[100000];
for(int i = 0; i < 100000; i++)
    array[i] = new int[100000];


then youll have a 2 dimensional array, containing a total of 1010 ints

But why would you even need 1010 ints?

pointers point to the start of an array by the way, theres not a big difference between a pointer to an array and an actual array

do know that this code will take up more or less than 40 GB of ram, so, good luck lol..
Last edited on
@Rampage

You have first pointed the pointer p to the location of q

After that you are trying to access the memory locations adjacent to q

But those memory locations may not be a part of your program's memory location.

The program runs because there is no boundary check feature in c++.

for (i=1; i<=n; i++) cin>>*(p+i);


This code is illegally accessing the memory locations that are not part of your program.




@Skillless
I needed that number of spaces for solving a problem at a contest. Anyway i didn't realized the size of memory it requires. So thx for pointing that out.

@harsh
is there any way i create a memory location each time i introduce a value? So that there always is a free memory location after the last introduced value?
If you needed 10^10 array elements to solve it, your solution was probably wrong. There is certainly another solution.

If I understand your question, you want to create a dynamically resizing array. Vectors should do it. http://www.cplusplus.com/reference/stl/vector/
Yes i realized that the solution was bad after i saw the required size. Thx for the link.
Topic archived. No new replies allowed.