-5

Why is this code not working and what should be the correct code?

#include <iostream>
using namespace std;

int get(int arr, int i)
{
    if(i >= 0 && i < sizeof(arr))
        return arr[i];
    return -1;
}

int main()
{
    int arr[3] = {10,20,30};
    cout << get(2) << endl;

    return 0;
}

Can someone explain?

susanth29
  • 397
  • 1
  • 1
  • 17
Pranav
  • 1
  • 1
    Welcome to SO! You should always provide all the code as text. Hint: you can still edit it into the post. – rawrex Aug 11 '21 at 09:19
  • 1
    There is much wrong with `get(2)`. I'd suggest to get a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) to support your learning. – churill Aug 11 '21 at 09:20

2 Answers2

1

Your get function takes two parameters, the array and the index. But to pass an array as a parameter, the function should be declared as.

int get(int arr[], int i){
    //whatever
}

When calling in main function, you only passed one. Instead of writing

std::cout << get(2) << std::endl;

You should have written

std::cout << get(arr, 2) << std::endl;
susanth29
  • 397
  • 1
  • 1
  • 17
Karen Baghdasaryan
  • 1,321
  • 4
  • 19
-1

I edited your code in calling to the main function and also passing the array to the get function is syntax error.

#include<iostream>
using namespace std;
int get(int arr[],int i)
{
if(i>=0 && i<sizeof(arr))
    return arr[i];
return -1;
}
int main()
{
int arr[3] = {10,20,30};
cout<<get(arr,1)<<endl;
return 0;
}
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/low-quality-posts/29570496) – rveerd Aug 11 '21 at 14:33
  • @rveerd I am new to the community. Can you explain how this answer is not satisfactory for this question. – susanth29 Aug 12 '21 at 05:47