Problems with Pointers in C++

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
lnr
Experienced poster
Posts: 142
Joined: Sat Jun 30, 2007 2:52 pm
Location: Dhaka,Bangladesh

Problems with Pointers in C++

Post 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;
}
mf
Guru
Posts: 1244
Joined: Mon Feb 28, 2005 4:51 am
Location: Zürich, Switzerland
Contact:

Re: Problems with Pointers in C++

Post 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.)
lnr
Experienced poster
Posts: 142
Joined: Sat Jun 30, 2007 2:52 pm
Location: Dhaka,Bangladesh

Re: Problems with Pointers in C++

Post 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.
Last edited by lnr on Fri Oct 17, 2008 9:12 pm, edited 2 times in total.
mf
Guru
Posts: 1244
Joined: Mon Feb 28, 2005 4:51 am
Location: Zürich, Switzerland
Contact:

Re: Problems with Pointers in C++

Post 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.
Post Reply

Return to “C++”