Search code examples
c++algorithmdata-structuresdeque

Why can't I access the size of this C++ array?


I am new to C++, and I am trying to write a function to solve this challenge. The code I have looks like this:

#include <iostream>
#include <deque> 
#include <algorithm>
using namespace std;

void printKMax(int arr[], int n, int k){
    deque<int> subarray;
    int i = arr.size();
    int maxValues[n];

    while(i >= 0) { 
        while (subarray.size() < n) {
            subarray.push_back(arr[i]);
            arr.pop();
            --i;
        }
        maxValues.push(max_element(begin(subarray), end(subarray)));
        subarray.pop_front();
    }

    for (array<int>::iterator it=maxValues.begin(); it!=maxValues.end(); 
it++) { 
        cout << maxValues[*it] << " ";
    }

}

int main(){

    int t;
    cin >> t;
    while(t>0) {
        int n,k;
        cin >> n >> k;
        int i;
        int arr[n];
        for(i=0;i<n;i++)
            cin >> arr[i];
        printKMax(arr, n, k);
        t--;
    }
    return 0;
} 

This code is throwing, among other things, an error saying:

"request for member ‘size’ in ‘arr’, which is of non-class type ‘int*’ int i = arr.size();"

Can someone please help me understand what this means? Am I trying to reference something from outside of the class, so that I need to use a pointer? Is it a problem with the way the array is declared?

Thanks in advance!


Solution

  • A C-style array isn't an object and you can't call size on it. It degenerates to nothing more than a pointer, and if you pass it here

    void printKMax(int arr[], int n, int k){
    

    Then this function doesn't even know the size. To solve the problem, you need to pass the size separately, as another parameter. Alternatively, you could just use a data structure such as std::vector instead, I would recommend this over using a plain array in this situation. Instead of int arr[n]; you would have std::vector<int> arr;. You can then query the size of the std::vector in your printKMax function. Accessing the vector uses the same syntax as accessing an array, and filling the vector works similar to how you're doing it now, with cin >> arr.