0

Beginner in c++ here.

why do i get the following error message when i run this code?

mismatched types 'const _Tp [_Nm]' and 'int*'

#include <bits/stdc++.h>

using namespace std;

void f(int arr[]){
    int arr_size = size(arr);
    for (int i = 0; i < arr_size; i++){
        cout << arr[i] << " ";
    }
}

int main(){
    int array[5] = {1,2,3,4,5};
    f(array);
    return 0;
}

I tried this and it works as expected.

#include <bits/stdc++.h>

using namespace std;

int main(){
    int array[5] = {1,2,3,4,5};
    int arr_size = size(array);
    for (int i = 0; i < arr_size; i++){
        cout << array[i] << " ";
    }
    return 0;
}

Can someone explain what went wrong and how to fix it? Thanks.

jayjay
  • 1
  • `int arr_size = size(arr);` you can do that in a function. `arr[]` decays to a pointer when passed as a parameter. Use `std::vector` instead of c-arrays – drescherjm Nov 07 '22 at 22:05
  • 4
    never ever include bits/anything – pm100 Nov 07 '22 at 22:06
  • 1
    std::size does not work on a pointer, which is what you have when array is passed to a function, use std::vector – pm100 Nov 07 '22 at 22:08
  • This error is, by the way, one of the best reasons to use `std::size`. If you went with the ol' `sizeof` trick, it gives the "wrong" result at runtime. No warning, no error, just the wrong result. – user4581301 Nov 07 '22 at 22:18

0 Answers0