Sarun
Sarun

Reputation: 1

Passing array as parameter in C++ ERROR

I tried to "select sort" an array. But instead of displaying the original array with just a "for loop", to go beyond the normal way and implement the stuffs I learned I decided to pass the original array to a function called "org_array" and tried to invoke it in the "void main()". But got couple of errors. I can't figure out what's the error I made in passing the parameters. Help please?

Code:

#include<iostream>
#include<conio.h>
using namespace std;
extern int s;
void org_array(int arr[30],int y);
void main()
{
    int i,n,j,pos,a[30];
    cout<<"Enter n: "<<endl;
    cin>>n;
    cout<<"\nEnter array: "<<endl;
    for(i=0;i<n;i++){   
            cin>>a[i];
    }
    cout<<"Orginal Array: ";
    org_array(a[30],n);
    /*for(i=0;i<n;i++){ 
            cout<<a[i]<<" | ";

    }*/
    for(i=0;i<n-1;i++)
    {
        int small=a[i];
        pos=i;
        for(j=i+1;j<n;j++)
        {
            if(a[j]<small)
            {
                    small=a[j];
                    pos=j;
            }
        }
        int temp=a[i];
            a[i]=a[pos];
            a[pos]=temp;

    }
    cout<<"\tSorted Array: ";
    for(i=0;i<n;i++){   
            cout<<a[i]<<" | ";
    }
    getch();
}
void org_array(int arr[30],int y){
    for(s=0;s<y;s++)
    {
        cout<<" "<<arr[s];
    }
}

Upvotes: 0

Views: 82

Answers (2)

Wait
Wait

Reputation: 36

In your code:

cout<<"Orginal Array: ";
org_array(a[30],n);

Should pass just the name of array as argument. Arrays are passed as reference to address of block of memory. You are referring to a specific index in array in your call. http://www.cplusplus.com/doc/tutorial/arrays/

org_array(a,n);

In your code:

void org_array(int arr[30],int y){
for(s=0;s<y;s++)
{
    cout<<" "<<arr[s];
}
}

for loop requires a type for variable s. I assume you want an integer.

for(int s=0; s<y; s++)

Your main function should also be of type int and return int value.

Upvotes: 1

Sadique
Sadique

Reputation: 22821

org_array(a[30],n);

is incorrect. It should be:

org_array(a,n);

And main should return int as per ISO. Further your declarations and definitions respectively should be this way:

void org_array(int [],int); // declaration - removed 30 since we might want to pass an array of larger size

void org_array(int arr[],int y) //definition
{
    for(int s=0;s<y;s++)  // You did not declare s as int
    {
        cout<<" "<<arr[s];
    }
}

Just a side note:

An lvalue [see question 2.5] of type array-of-T which appears in an expression decays (with three exceptions) into a pointer to its first element; the type of the resultant pointer is pointer-to-T because an array is not a "modifiable lvalue,"

(The exceptions are when the array is the operand of a sizeof or & operator, or is a literal string initializer for a character array.)

Upvotes: 3

Related Questions