passing char[256] by reference and wanting to cout the result

I am trying to pass a char by reference and cout the results

void display()
{
int month = 1;
char nameOfMonth[256];
displayMonth(month, nameOFMonth);

// I want to be able to cout the name of the month
cout << "Month is: " << nameOfMonth << endl;
}

void displayMonth(int month, char monthName[])
{
if (month == 1)
monthName = "January";

}

None of this is working. I think I'm correct in believing that nameOfMonth is passed by reference. How do I assign it a value in the second function? I can't use a string or an array except for the char[256] array. I have a feeling that the problem lies in monthName = "January" but I don't know what to do instead.
Last edited on
I think I'm correct in believing that nameOfMonth is passed by reference.
No, it's a pointer. monthName = "January" assigns the pointer of "January" to the local variable monthName.

To copy a string use strcpy(...):
http://www.cplusplus.com/reference/cstring/strcpy/?kw=strcpy
Look VERY VERY carefully at that line
displayMonth(month, nameOFMonth);
It should be
displayMonth(month, nameOfMonth);
What a huge difference the case of the letter F (should be f) makes!


The rest of what @coder777 says is absolutely true. For a C-string you can't assign it EXCEPT when it is originally declared, which is why you have to use strcpy(). However, you could do this for the newer 'string' type (one of the reasons for introducing them, although there are more and better): consider using this.

Corrected your error and added @coder777's suggestion for the code below (had to add the headers and change to int main()).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<iostream>
#include<cstring>
using namespace std;
void displayMonth(int month, char monthName[]);


int main()
{
   int month = 1;
   char nameOfMonth[256];
   displayMonth(month, nameOfMonth);

   // I want to be able to cout the name of the month
   cout << "Month is: " << nameOfMonth << endl;
}

void displayMonth(int month, char monthName[])
{
   if (month == 1)
//    monthName = "January";  // not allowed - can't assign except in declaration
      strcpy( monthName, "January" );
}


In terms of what you originally asked, you aren't passing monthName[] by value, you are passing ... a pointer to monthName[] ... by value. This is "like" passing by reference. (I'm trying to choose my words very carefully here - I'm not a professional programmer!)
Last edited on
Thank you for the help! This made my program work. Thanks for the heads up on the F. I would have caught that in the real program. I retyped it here--not copy and paste. I have read about the dangers of using strcpy because you may exceed the buffer, but in this case where I know for sure that I won't exceed the buffer, strcpy is great! Thanks to both of you!
Topic archived. No new replies allowed.