My Code:
#include <iostream>
#include <cstdlib>
using namespace std;
int *p;
void fun(int *arr, int n)
{
p = (int *)malloc(sizeof(int) * (n + 1));
cout << sizeof(p) / sizeof(int) << " " << sizeof(p) << " " << sizeof(int) << endl;
}
int main()
{
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
cin >> arr[i];
fun(arr, n);
return 0;
}
Input:
4
2 1 4 3
Output:
2 8 4
Expected Output:
5 20 4
The code returns an incorrect value of the size which is being allocated to the array using malloc. I identified this problem when I used memset(p, -1, sizeof(p)))
and the array was incorrectly initialized. Please help. Thanks in advance.