I want to find size of a dynamically allocated array in my following code :
Expand|Select|Wrap|Line Numbers
- #include <iostream>
- #include <cstdlib>
- using namespace std;
- int main()
- {
- int *Set = NULL;
- int element;
- char Choice;
- int n = 0;
- do
- {
- cout << " Enter an element : ";
- cin >> element;
- n++;
- Set = (int *)realloc(Set, n * sizeof(int));
- Set[n - 1] = element;
- cout << " Do you want to enter another element? (y/n) : ";
- cin >> Choice;
- } while (Choice == 'y' || Choice == 'Y');
- cout << " Size of the array : " << sizeof(Set)/sizeof(int) << endl;
- return 0;
- }
tapas@My-Child:~/Programming/Set Intersection$ ./test.o
Enter an element : 1
Do you want to enter another element? (y/n) : y
Enter an element : 2
Do you want to enter another element? (y/n) : y
Enter an element : 3
Do you want to enter another element? (y/n) : n
Size of the array : 1 <-- But the size should be 3!!
The reason behind this behavior is, Set is a integer pointer which points to a chunk of contiguous memory block and using sizeof(Set)/sizeof(int) I am getting the size of the pointer (am I wrong?). But how can I can the size of allocated memory, I also try it sizeof(*Set)/sizeof(int), but the result is same. And
Expand|Select|Wrap|Line Numbers
- cout << " Size of the array : " << n << endl;