C dynamic memory allocation and sizeof()

前端 未结 7 1554
感情败类
感情败类 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:33

    *arr is not the same as arr[8] since it's size is not known in compile time, and sizeof is a function of the compiler. So when your arr is *arr sizeof will return the size of the pointer (sizeof(int *))in bytes, while when your arr is arr[8], the sizeof will return the size of array of 8 integers in bytes (which is sizeof(int) * 8).

    When you pass a pointer to array to a function, you must specify its size, because the compiler can't do it for you. Another way is to end the array with null element, and perform a while loop.

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