I am trying to change the value of my char array[10] within a switch statement such that, if we have case 1, my char array[10]=”january”, or if we have case 2, then array[10]=”february” and so on. The problem is that i get error message, and i know that I am doing something wrong. any help will be very appreciated. here is my switch statement written in Dev-C++.
char month[10];
switch (i)
{
case 1:
month[10]="January";
cout<<month<<endl;
break;
case 2:
month[10]="February";
cout<<month<<endl;
break;
}
When you create strings like
"January"or"December"the compiler is generating aconst char *which points to a constant array of characters that has a0at the end the integer not the character.Your code is trying to assign
"January"‘s address to the 11th element in the array, which it doesn’t have because arrays start at 0.This has a couple problems, First, the elements of
month[]are characters, not character pointers. Second, arrays start at 0 so you were looking to usemonth[9], though that still would have been wrong.What you are looking to do is copy each character into the array, there are functions that do this like
strcpybut try it with aforloop first to give yourself a better sense of what is going on.Another way to solve this problem, and probably the way you’re after is to change
monthfrom a character array of a fixed size, to achar *that way you can use your earlier method ofmonth = "January"its how I would prefer to do it myself, because it only uses up as much memory as I need and the syntax is cleaner, though you should know how to do both methods.