great element and its index

dear all first I want to say hi for every Im new in C++ programing and I hope to find help here i've create the small function to type the great numbe of an arry and its index but when I run it its showing only the intial value which I give the code

#include<iostream>
using namespace std;
void G(int [],int&);
int main()
{
int in;
int a[]={4,5,2,12,67,9,0,13};
G(a,in);
cin.get();
}
void G(int b[],int& index)
{index=0;
int size=sizeof(b)/sizeof(int);
int g=b[index];
for(int j=index+1;j<size;j++)
{
if(g<b[j])
{ g=b[j];
index=j;}
}
cout<<"great element"<<g<<"great index"<<index<<endl;

}



so could someone show me whats wrong ??
im getting great element 4 and index zero
This void G(int b[],int& index) provides only a pointer to the array. You cannot determine the size of the array with sizeof. Pass another parameter to the function that contains the size: void G(int b[],int size,int& index)
Since you're new to C++, you may not yet know that C++ already has this function. It's called max_element()

Also, as already mentioned, the function argument "int b[]" is a bit misleading: what really is passed in your case is a pointer to the first element of the array. Which is why sizeof(b)/sizeof(int) does not give you the size of the array (it gives you the size of a pointer divided by the size of an int, which is apparently 1 in your case).

If you're using C-style array passing (as pointer to first element) you have to pass array size as another parameter, as already mentioned, or another pointer to indicate the end of the array:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <algorithm>
void G(int* beg, int* end)
{
    int* p = std::max_element(beg, end);
    std::cout << "great element " << *p << " great index " << p-beg << '\n';
}
int main()
{
    int a[]={4,5,2,12,67,9,0,13};
    G(std::begin(a), std::end(a)); // older compilers use: G(a, a+sizeof a/sizeof *a);
}
online demo: http://ideone.com/ng8UY

alternatively, you could pass a reference to an array, or use vectors, which should be used from the start anyway.
thank you verry much now its clear for me.
Topic archived. No new replies allowed.