0

When I write the code it shows error

#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    int arr[] = {12, 3, 4, 15};
    int n = arr.size();
    
    cout << "Size of array is " << n;
    return 0;
}




Compilation failed due to following error(s).
main.cpp:7:17: error: request for member ‘size’ in ‘arr’, which is of non-class type ‘int [4]’

    7 |     int n = arr.size();
      |                 ^~~~

it also didn't work for vector array i tried that also can't understand the problem

4
  • 1
    Use a std::vector<int> instead of a raw array. Commented Mar 18, 2022 at 10:28
  • 1
    You can also use sizeof(arr)/sizeof(arr[0]) or the non standard _countof(arr) which exists on some platforms. Commented Mar 18, 2022 at 10:37
  • "it also didn't work for vector array": what is a vector array? Commented Mar 18, 2022 at 10:40
  • 2
    #include <bits/stdc++.h> -- I know you didn't get this from a reputable C++ book, which you should be using to learn C++. Instead, you probably got code from a dodgy C++ website and used this non-standard header. Commented Mar 18, 2022 at 13:00

2 Answers 2

6

As a rule of thumb, use

std::vector<int> arr = {12, 3, 4, 15};

with

arr.size();

returning the number of elements, unless you have a good reason not to.

Failing that, std::size(arr) will give you the number of elements, but only if arr has not already decayed to a pointer type by virtue of your receiving it as a function parameter. That C++ standard library function does something clever to obviate the normal pointer decay you observe with C-style arrays.

Sign up to request clarification or add additional context in comments.

Comments

5

C-array doesn't have methods.

Since C++17, you might use std::size:

const auto n = std::size(arr);

4 Comments

int for the type. Really?
@Bathsheba Why is that problematic?
@PasserBy int can be as small as [-32767, 32767] (C++20 gives you an extra negative) and vulnerable to overflow.
@Bathsheba: I used int as OP. Changed to auto.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.