C dynamic memory allocation and sizeof()

前端 未结 7 1553
感情败类
感情败类 2020-12-12 02:42

I\'m having some trouble understanding the difference between these two code segments: I allocate space for an array of integers dynamically within my code with the followin

相关标签:
7条回答
  • 2020-12-12 03:10

    well, int *arr declares a pointer, a variable which keeps the address of some other variable, and its size is the size of an integer because it's a pointer, it just have to keep the address, not the pointee itself.
    int arr[8] declares an array, a collection of integers. sizeof(arr) refers to the size of the entire collection, so 8*sizeof(int).
    Often you hear that "array and pointers are the same things". That's not true! They're different things.

    0 讨论(0)
  • 2020-12-12 03:19

    sizeof(arr) is the same as sizeof(int*), i.e. the size of a single pointer. You can however calculate arr_sz as ... cnt!

    0 讨论(0)
  • 2020-12-12 03:19

    If you have int arr1[8] the type of arr1 (as far as the compiler is concerned) is an array ints of size 8.

    In the example int * arr2 the type of arr2 is pointer to an integer.

    sizeof(arr1) is the size of an int array
    sizeof(arr2) is the size of an int pointer (4 bytes on a 32 bit system, 8 bytes on a 64 bit system)

    So, the only difference is the type which the compiler thinks that variable is.

    0 讨论(0)
  • 2020-12-12 03:25
    int *arr;   ----> Pointer
    int arr[8]; ----> Array
    

    First up what you got there - int *arr is a pointer, pointing to some bytes of memory location, not an array.

    The type of an Array and a Pointer is not the same.

    In another function where I pass in arr, I would like to determine the size (number elements) in arr. When I call

    int arr_sz = sizeof(arr)/sizeof(int);
    

    it only returns 1, which is just the number of bytes in an int for both arguments I am assuming (4/4)=1. I just assumed it would be the same as using an array

    Even if it is assumed to be an Array -- that's because Arrays get decayed into pointers when passed into functions. You need to explicitly pass the array size in functions as a separate argument.

    Go through this:

    Sizeof an array in the C programming language?

    There is a difference between a static array and dynamic memory allocation.

    The sizeof operator will not work on dynamic allocations. AFAIK it works best with stack-based and predefined types.

    0 讨论(0)
  • 2020-12-12 03:26

    You can't use sizeof with memory pointers:

    int *arr = calloc(cnt, sizeof(int));
    

    But it's ok to use it with arrays:

    int arr[8];
    
    0 讨论(0)
  • 2020-12-12 03:30

    Mike,

    arr is a pointer and as such, on your system at least, has the same number of bytes as int. Array's are not always the same as pointers to the array type.

    0 讨论(0)
提交回复
热议问题