size of array in c

后端 未结 6 1328
伪装坚强ぢ
伪装坚强ぢ 2020-12-01 20:59

a simple question that bugs me. Say I have an array defined in main like so int arr[5]. Now, if I\'m still inside main and I set int i = sizeof(arr)/sizeo

6条回答
  •  没有蜡笔的小新
    2020-12-01 21:29

    You should understand the difference between static and dynamic arrays. Static arrays are types like int, float, double etc. They are different. Even

    int a[10];
    

    has a different type from

    int b[11];
    

    At compile time, the number of elements in static arrays are known and the sizeof operator returns the number of bytes they occupy.

    With pointers that were initialized, either to point to some variable, or to an allocated memory, it is at run-time that it would be apparent where they are pointing to and the compiler cannot determine what would be the size of that array in the future. Therefore, the sizeof a pointer gives you 4 (or 8 in 64bits systems for example).

    Note that sizeof operator works at compile-time and not at run-time.

    If you need to know the size of an allocated memory (through malloc), you have no choice but to save the size of the array in another variable, for example right after you did the malloc.

提交回复
热议问题