Page 1 of 1

Problems with Pointers in C++

Posted: Mon Oct 06, 2008 2:16 pm
by lnr
I tried to dinamically allocate memory for pointer array.
There is no compile time error.
But it has runtime error.
I don't know how to fix it.
Someone please help.

Here is the code.

#include<iostream>
#include<algorithm>
using namespace std;

int main()
{
int *arr,ind,i;
ind=0;
for(i=1;i<=10;i++)
{
arr=new int;
arr[ind++]=i;
}
for(i=0;i<ind;i++)
cout<<arr<<' ';
cout<<endl;

return 0;
}

Re: Problems with Pointers in C++

Posted: Mon Oct 06, 2008 4:59 pm
by mf
You should've used "new int[10]" instead of "new int". The former allocates an array, while the latter allocates just a single element of type int.

And of couse, "arr = new int[10];" should be done before the loop in which it is used, and deallocated before main() finished, or else you'll have a memory leak. (Or better yet, use scoped_array if it's supported in your environment.)

Re: Problems with Pointers in C++

Posted: Mon Oct 06, 2008 6:07 pm
by lnr
Thanks mf.

If I declare like that
int *arr;
arr=new int[105];
Then it is like
int arr[105];
It is working.
But is it possible to increase the size of array by one before i try to take an input.

You mentioned about scoped_array.
I have not heard about this.
Would you please tell me about this in detail?
Thanks again.

Re: Problems with Pointers in C++

Posted: Mon Oct 06, 2008 6:15 pm
by mf
But is it possible to increase the size of array by one before i try to take an input.
I'd suggest you allocate the array before you try to take the input.

I don't know any way to resize a new[]-allocated array other than to create a new copy of it and delete the original. malloc()/realloc()/free() would perhaps suit your needs better if you need to do reallocation frequently.

You mentioned about scoped_array.
I have never heard about this.
Would you please tell me about this in detail?
Google is your friend.