rpshwin
rpshwin

Reputation: 341

C++ passing char array to function

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.

Upvotes: 24

Views: 86581

Answers (6)

jmmartinez
jmmartinez

Reputation: 343

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;

Upvotes: 7

Mysticial
Mysticial

Reputation: 471229

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

Upvotes: 12

Loki Astari
Loki Astari

Reputation: 264381

Arrays devolve into pointers when passed as parameters.
So the simple way that you want is:

char* myfunc(char* myname1)
{
    return myname1;
}

If you were going to show off you can pass the array by reference.
But if you can't read ahead you will not be able to use this.

char* myfunc(char (&myname1)[12]) // Note you can only pass arrays of size 12
{                                // to this function so it is limited in use.
    return myname1;
}

TO make it more useful though you could template it:

template<int SIZE>
char* myfunc(char (&myname1)[SIZE])
{
    return myname1;
}

Upvotes: 7

Alex Force
Alex Force

Reputation: 9

void myfunc(char& ); is the problem it should take in a char * and not a char reference which is what you did.

and in the function use strcpy(char * destination, char *source);

Upvotes: 0

John Humphreys
John Humphreys

Reputation: 39284

Pass it as a char* instead of a char&. You're passing a reference to a single character instead of a pointer to a character array in this code.

Also use strncpy (google it) to set the value of tr char* once you're in the function.

Upvotes: 0

Martin Beckett
Martin Beckett

Reputation: 96109

myname1 = "Billy" doesn't copy a string it copies a pointer to the constant local memory containing "Billy"

Take a look at strncpy() or memcpy()

Upvotes: 0

Related Questions