-2
#include <iostream>

using namespace std;

int main (void)
{
    int * p = new int(40);  // here `p` points to an array having space for 40 ints or space allocated is 40 bytes?
    for (int i = 0; i < 2; i++)
        cin>>p[i];
    cout<<sizeof(p)<<"\n";   // here, the output should be size of array since p points to an array
    int arr[5] = {1,2,3,4,5}; // since, here it will output 20 (space allocated for the entire array)
    cout<<sizeof(arr)<<"\n";
    return 0;
}

So, I have two questions (the first two comments in the program)

  1. Here p points to an array having space for 40 ints or space allocated is 40 bytes?

  2. Here, the output should be size of array since p points to an array because technically speaking, arr is also a pointer and when we do *arr it references to the first element of the array.

John Lui
  • 1,434
  • 3
  • 23
  • 37

3 Answers3

3

In your code, p is defined as a pointer, so sizeof(p) is the same as sizeof(int*), with is 4 on 32bit systems and 8 on 64bit systems.

In the second case, arr is a static array, so sizeof(arr) is the same as sizeof(int[5]) which returns 5*sizeof(int), assuming there's no padding or other complex work happening "under the hood".

Note that when you pass an array name as an argument to a function which accepts a pointer as a formal function parameter, the array "decays" to a pointer, so calling sizeof on an argument yields behavior you likely did not expect. For example:


Code Listing


#include <stdio.h>

void printSize(int* arg);

int main(void)
{
    int *p;
    int arr[10];
    printf("sizeof p:%d\n", sizeof(p));
    printf("sizeof arr:%d\n", sizeof(arr));
    printSize(p);
    printSize(arr);

    return 0;
}

void printSize(int* arg)
{
    printf("sizeof arg:%d\n", sizeof(arg));
}

Sample Output


sizeof p:8
sizeof arr:40
sizeof arg:8
sizeof arg:8
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Cloud
  • 18,753
  • 15
  • 79
  • 153
3

When you say int *p = new int(40); you are actually allocating space for a single integer and filling that space with the integer 40. If you want an array of 40 integers, you should use square brackets:

int *p = new int[40];

So, to answer question #1: neither. The space allocated is the size of one int on your system.

To answer question #2: the first line of output is the size of a single pointer on your system (because p is just a pointer). This will probably be the same as the size of an int, which is likely 4 bytes. The second line of output will be the total allocation size of your array of integers, so it will be 40*sizeof(int), or 160.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Jashaszun
  • 9,207
  • 3
  • 29
  • 57
1

Your two uses of sizeof are querying the size of the types int* and int[5] respectively.

(also, you have a bug and meant new int[40], not new int(40), but that doesn't affect the results of sizeof)