I would rather just use a string, but we aren't supposed to as the teacher hates them and wants us to figure out ways to avoid them. So I looked into using a struct, but we aren't that far in the book and she hates it when I skip ahead. So I was thinking of doing this:
#include <iomanip>
#include <iostream>
#include <stdio.h>
using namespace std;
void myfunc(char& );
int main()
{
char myname[12];
cout<<"enter a name ";
cin>>myname;
cout<<"myname is "<<myname;
cout<<"myname is " << myfunc(myname);
getchar();
getchar();
return 0;
}
void myfunc(char &myname1)
{
myname1 = "Billy"
}
But this doesn't work and I don't know why.
How Arrays are Passed to Functions in C/C++? 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().
An array can be passed to functions in C using pointers by passing reference to the base address of the array and similarly, a multidimensional array can also be passed to functions in C.
One way is to do it like this:
void myfunc(char *myname1)
{
strcpy(myname1,"Billy");
}
You will also need to change your main to:
myfunc(myname);
cout<<"myname is " << myname;
However you have to be careful not to overflow your initial buffer.
The reason why your original code doesn't work is because you can't assign strings to char
pointers. Instead you must copy the string to the char*
.
This line of code is wrong:
cout<<"myname is " << myfunc(myname);
myfunc()
doesn't return anything, its return type is void
.
Try using:
char* myfunc(char *myname1)
{
strcpy(myname1,"Billy");
return myname;
}
Or
myfunc(myname);
cout<<"myname is " << myname;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With