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;
}
Problems with Pointers in C++
Moderator: Board moderators
Re: Problems with Pointers in C++
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.)
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++
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.
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.
Last edited by lnr on Fri Oct 17, 2008 9:12 pm, edited 2 times in total.
Re: Problems with Pointers in C++
I'd suggest you allocate the array before you try to take the input.But is it possible to increase the size of array by one before i try to take an 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.
Google is your friend.You mentioned about scoped_array.
I have never heard about this.
Would you please tell me about this in detail?