Tiramisu
Tiramisu

Reputation: 31

Passing character array?

I am having trouble passing my char array to a function. Whenever I try to do so, I get an error displaying the following :

Error 1 error C2664: 'void Print(char)' : cannot convert argument 1 from 'char [22]' to 'char'

I'm not sure what the issue could be. Some advice would be great.

#include <iostream>

using namespace std;

void Print(char);

int main(){
    char arr1[] = { "Hello how are you? / " };
    Print(arr1);
}

void Print(char arr[]){
    for (char i = 0; i != '/'; i++)
    {
        cout << arr[i] << endl;
    }
}

Upvotes: 1

Views: 67

Answers (2)

James Nimmo
James Nimmo

Reputation: 33

This program works.

#include <iostream>
#include <string>

using namespace std;

void Print(char *arr);


int main()
{
char arr1[] = { "Hello how are you? / " };
Print(arr1);

    return 0;
}

void Print(char *arr) {

int i = 0;

while (arr[i] != '/')
{
    cout << arr[i] << endl;
    ++i;
}


}

I feel that a while statement is better here than a for statement and you need to use arr as a pointer.

Upvotes: 1

songyuanyao
songyuanyao

Reputation: 172924

1.Function declaration and definition of Print don't match. According to the declaration, Print accepts char as its argument, that's why compiler complains. Change the declaration to

void Print(char[]);

2.for (char i = 0; i != '/'; i++), the condition i != '/' doesn't check the element of char array, it should be arr[i] != '/'.

Upvotes: 3

Related Questions