Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing char array into a function

How do you pass a char array into a function.

declarations

char fromName[64];
char fromStreet[64];
char fromSuburb[64];
char fromCountry[64];

function call

    Trans[i]->putAddress(fromName, fromStreet, fromSuburb, fromCountry);

prototype

void putAddress(char,char,char,char);

function    
void putAddress(char fName,char fStreet,char fSuburb,char fCountry){

        return;
}

and Error "main.cpp", line 86: Error: Formal argument 1 of type char in call to Mail::putAddress(char, char, char, char) is being passed char*.

like image 805
Daniel Del Core Avatar asked Apr 30 '12 12:04

Daniel Del Core


People also ask

How do you pass a char array to a function?

A whole array cannot be passed as an argument to a function in C++. You can, however, pass a pointer to an array without an index by specifying the array's name. In C, when we pass an array to a function say fun(), it is always treated as a pointer by fun().

Can you pass an array into a function C++?

C++ does not allow to pass an entire array as an argument to a function. However, You can pass a pointer to an array by specifying the array's name without an index.


1 Answers

You pass strings (arrays of characters) as a pointer to the first character of the array:

void something(char *str) { /* ... */ }

int main(int argc, char **argv) {
    char somestring[] = "Hell World!\n";

    something(somestring);

    return 0;
}

Because arrays automatically decay to pointers when passed to a function all you have to do is pass the character array and it works. So in your example:

void putAddress(char*, char*, char*, char*);
like image 151
orlp Avatar answered Oct 13 '22 13:10

orlp