-
strcpy
I'm trying to copy some strings into a char* array, I've been trying to use strcpy, only when I do, the program crashes. The array is initialized, within a class, as:
char* Commands[MAXNUMBER]
//maxnumber is defined earlier to have a value of 10
Then I am trying to intitalize the array within the constructor funcion as follows:
strcpy(Commands[0], "status");
strcpy(Commands[1], "load");
strcpy(Commands[2], "coffee");
strcpy(Commands[3], "chocolate");
strcpy(Commands[4], "soup");
strcpy(Commands[5], "quarter");
strcpy(Commands[6], "dime");
strcpy(Commands[7], "nickel");
My first instinct told me to make the array 2 dimensional, but that did not work. How can I scan the strings into the array without having the program crash when I get to this part of the code?
-
the function strcmp is not going to be your answer. It only compares functions.
-
One way of declaring the array is:
char Commands[MAXNUMBER][20];
Or if you want to fill the array when it is declared, instead of using strcpy, then you can declare the array like this:
char* Commands[MAXNUMBER] = {
"status","load","coffee","chocolate","soup","quart er","dime","nickel"};
-
i meant that it compares strings. Sorry!!:D :D
-
This declaration does not reserve memory for the strings to be copied into:
char* Commands[MAXNUMBER];
This does:
char Commands[MAXNUMBER][MAXLENGTH];
assuming MAXLENGTH is defined similar to MAXNUMBER. Alternatively you could use:
char ** Commands;
and use dynamic memory to declare the space or use
char * Commands[MAXNUMBER] = //and initialize it here as in a previous post because now the compiler decides what MAXLENGTH wil be.
Whichever mechnaism you use, the programmer must reserve the memory before they try to use it, or else bad things will happen.