Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ passing char array to function

Tags:

c++

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.

like image 300
rpshwin Avatar asked Nov 07 '11 02:11

rpshwin


People also ask

Can you pass a char array to function in C?

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().

Can we pass array to the function?

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.


2 Answers

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*.

like image 109
Mysticial Avatar answered Sep 28 '22 22:09

Mysticial


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;
like image 41
jmmartinez Avatar answered Sep 28 '22 22:09

jmmartinez