Thread: strcmp

  1. #1
    Registered User
    Join Date
    Nov 2001
    Posts
    8

    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?
    Last edited by coug2197; 01-31-2002 at 06:50 PM.

  2. #2
    ¡Amo fútbol!
    Join Date
    Dec 2001
    Posts
    2,138
    the function strcmp is not going to be your answer. It only compares functions.

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    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"};
    Last edited by swoopy; 01-31-2002 at 06:17 PM.

  4. #4
    ¡Amo fútbol!
    Join Date
    Dec 2001
    Posts
    2,138
    i meant that it compares strings. Sorry!!

  5. #5
    Unregistered
    Guest
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Fucntion returns -1, Why?
    By Taper in forum C Programming
    Replies: 16
    Last Post: 12-08-2008, 06:30 PM
  2. help with switch statement
    By agentsmith in forum C Programming
    Replies: 11
    Last Post: 08-26-2008, 04:02 PM
  3. problem with strings
    By agentsmith in forum C Programming
    Replies: 5
    Last Post: 04-08-2008, 12:07 PM
  4. help with strcmp
    By blork_98 in forum C Programming
    Replies: 8
    Last Post: 02-21-2006, 08:23 PM
  5. strcmp
    By kryonik in forum C Programming
    Replies: 9
    Last Post: 10-11-2005, 11:04 AM