0

Here is a code to print elements of an array. I am getting an error.Can anyone find out what is the problem with the code?

#include <iostream>

 using namespace std;

 int print_r(char arrName,int len){
            for(int i=0;i<len;i++){
                    cout<<arrName[i]<<"\t";        
            }
}

 int main(){

int a[3];
a[0]=1;
a[1]=2;
a[2]=3;

print_r(a,3);

return 0;
}    
TryinHard
  • 4,078
  • 3
  • 28
  • 54
Axeem
  • 670
  • 4
  • 16
  • 26

4 Answers4

2
int print_r(char arrName,int len)

should be

void print_r(int *arrName,int len)

you are not retuning anything so it should be void, not int, and you declared your array as integer why do you use char?

B.I.A
  • 700
  • 1
  • 7
  • 20
  • Can I use it for both `int` and `char`,I think it is not possible I need another Function for `char array` like `void print_r(char *arrName,int len)` Can I make one function for both??? – Axeem Jan 03 '14 at 05:37
  • other than overloading i am not aware of another way of using the same function for different arguments, have look at this answer http://stackoverflow.com/questions/429125/override-and-overload-in-c – B.I.A Jan 03 '14 at 05:52
  • Use a template if you want to call the function with different types - `template void print_r(const Type* arrName, std::size_t len)` – Captain Obvlious Jan 03 '14 at 17:27
1

It is an obvious error that you are passing int* to char argument in function. Hope this would help-

#include <iostream>

using namespace std;

void print_r(int arrName[],int len){
        for(int i=0;i<len;i++){
                cout<<arrName[i]<<"\t";        
        }
}

int main(){

int a[3];
a[0]=1;
a[1]=2;
a[2]=3;

print_r(a,3);

return 0;
}    

instead you can also define prototype as

void print_r(int *arrName, int len)
{
 //Function body lies here
}
TryinHard
  • 4,078
  • 3
  • 28
  • 54
1

Change::

int print_r(char arrName,int len){
     for(int i=0;i<len;i++){
     cout<<arrName[i]<<"\t";        
    }

To

int print_r(int* arrName,int len){ // You are passing int array to print_r
     for(int i=0;i<len;i++){
     cout<<arrName[i]<<"\t"; 
     return 0 ; // int print_r( int*, int ) will expect an int return value
    }
Abhineet
  • 5,320
  • 1
  • 25
  • 43
0

When defining your function int print_r, change the return type to void , that is,

int print_r(char arrName,int len){
        for(int i=0;i<len;i++){
                cout<<arrName[i]<<"\t";        
        }
}

//Instead use this
void print_r(char arrName,int len){
        for(int i=0;i<len;i++){
                cout<<arrName[i]<<"\t";        
        }
}
SoulRayder
  • 5,072
  • 6
  • 47
  • 93