-3

For example a code like:

int arr[5] = {1, 2, 3, 4, 5}

Is there anyway to get the 5 in arr[5]? I haven't learnt C++ before.

Buddy Christ
  • 1,364
  • 8
  • 22
cinos
  • 117
  • 2
  • 8
  • Have you tried `sizeof`? For an array that is an `int*`, I know that you can't. – donjuedo Feb 25 '20 at 22:51
  • 1
    Make up your mind. You have a C tag on the question and you reference C++ in your post. – jwdonahue Feb 25 '20 at 22:56
  • 1
    @donjuedo : _"an array that is an `int*`"_ is an oxymoron - a pointer is not an array. here `sizeof(arr) / sizeof(*arr) == 5`. – Clifford Feb 25 '20 at 22:56
  • @Clifford, I am pretty sure you have a solid of C and how it handles types. There's no need for me to split hairs about `array`. – donjuedo Feb 25 '20 at 23:00
  • I said that I haven't learned C++ before just in case people assumed I had learnt it. – cinos Feb 25 '20 at 23:23
  • 1
    @cinos : That is understood, but your question is tagged [C], so mentioning C++ is not relevant. Presumably you are equally inproficient in C? – Clifford Feb 26 '20 at 07:47
  • 1
    @donjuedo It is not splitting hairs. It is an important distinction, ant in the context of this question Irellavant. Your comment is likely to do more to confuse than to help. – Clifford Feb 26 '20 at 07:50

1 Answers1

4

You can get it by getting the array size and divide it by the size of a single element:

int arr[5] = {1, 2, 3, 4, 5};
size_t lengthOfArr = sizeof(arr)/sizeof(arr[0]) ;
Alberto Sinigaglia
  • 12,097
  • 2
  • 20
  • 48