How to determine the size of an array of strings in C++?

后端 未结 8 726
野的像风
野的像风 2020-12-30 06:57

I\'m trying to simply print out the values contained in an array.

I have an array of strings called \'result\'. I don\'t know exactly how big it is because it was au

8条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-30 07:27

    You cannot determine the size of an array dynamically in C++. You must pass the size around as a parameter.

    As a side note, using a Standard Library container (e.g., vector) allieviates this.

    In your sizeof example, sizeof(result) is asking for the size of a pointer (to presumably a std::string). This is because the actual array type "decays" to a pointer-to-element type when passed to a function (even if the function is declared to take an array type). The sizeof(result[0]) returns the size of the first element in your array, which coincidentally is also 16 bytes. It appears that pointers are 16 bytes (128-bit) on your platform.

    Remember that sizeof is always evaluated at compile-time in C++, never at run-time.

提交回复
热议问题