memory managment.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include<iostream>

using namespace std;



int *resize(int *old,unsigned int oldsize,unsigned int newsize)
{

    int *tmp=new(nothrow) int[newsize];

    if(newsize<oldsize)oldsize=newsize;

    for(int i=0;i<oldsize;++i)
    tmp[i]=old[i];

    delete[] old;
   return tmp;

}
int main()
{
 int *arr=new(nothrow) int[100];

 for(int i=0;i<100;++i)
 arr[i]=i;


 cout<<"The old size is:"<<sizeof(arr)/sizeof(arr[0]);
 arr=resize(arr,100,200);
 cout<<endl;
 cout<<"The new size is:"<<sizeof(arr)/sizeof(arr[0]);


}


Why print:
1
1
?


It should print
100(the old size)
200(the new size)

So what is the error with this?
thanks.
In your code arr is a pointer so sizeof(arr) will return the size of a pointer.
arr is an int pointer. Size probably four bytes, eight on a 64 bit system.
arr[0] is an int. Size probably four bytes, eight on a 64 bit system.

So
sizeof(arr)/sizeof(arr[0])
is 4/4, which is 1.
Ok but how i can tell it to print the old size and new btw.?
You can't. It doesn't keep track of that. You'll have to keep track of it yourself.
There is no way to get the size of the array though the pointer. You have to keep track of the size yourself.
But the size of array has change right?
Or not?
Last edited on
A new array has been made, that could be a different size, and the old array contents copied into it, and the pointer now points to the new array instead of the old array.

If you want to call that a changed array size, great. If you want to call it making a new array of different size and using the same pointer to get to it, also great. Up to you how you think of it so long as you understand what's happening.
Last edited on
Topic archived. No new replies allowed.