Search code examples
carraysstringcharacterstrcmp

strcmp string and character array in c


Here is the code I have. I'm trying to do a string comparison. A serial input reads what keys are pressed and sets cmd.command to what was typed on the keyboard. Then I take that and do a string comparison to see if it is a command that's within my list. What I'm stuck on is the string comparison.

typedef struct {
    const char *cmd;
    void (*cmdFuncPtr)(void);
}CmdStruct;

typedef struct {
    char command[16];
    char argument[16];
} Command;

Command cmd;

CmdStruct cmdStructArray[] = { {"led",      LEDHandler      },
                               {"relay",    RelayFunction    },  };

void ProcessCommand() {
    for (j = 0; j < sizeof(cmdStructArray)/sizeof(cmdStructArray[0]); j++) {
        if(strcmp(cmdStructArray[j].cmd, cmd.command) == 0) {
            // do stuff
        }
    }
}

If I type in "led", then these two printf statements print the same thing.

printf(cmdStructArray[0].cmd);
printf("%s", cmd.command);

How can I get the string comparison to work?


Solution

  • I found a fix, and now strcmp works. I changed the struct in the struct array. Now it's

    typedef struct {
        char cmd[16];
        void (*cmdFuncPtr)(void);
    }CmdStruct;
    

    I don't know why this works, and don't know what the difference is. The const char *cmd I had before is also a way to create a "string" in C.