简体   繁体   中英

What's wrong with this C library function usage?

I am trying to compare two char arrays. The DoSomething() function, however, never get's called. I can't figure out why.

What am I doing wrong?

//The value the user types in will be stored here:
char TempStorage[]={0,0,0,0,0,0};

//User types in a sequence here:
GetInput();

//One of the sequences that TempStorage will be compared to.
char Sequence[]={1,2,3,4,0,0};


//If the user typed in "123400" then DoSomething().
if(memcmp(TempStorage, Sequence, sizeof(TempStorage) == 0))
{
    DoSomething();
}

Misplaced paren.

if(memcmp(TempStorage, Sequence, sizeof(TempStorage) == 0))

should be

if(memcmp(TempStorage, Sequence, sizeof(TempStorage)) == 0)

Are those really six inputs that you parsed and placed in an array? Or is TempStorage a string of ASCII characters that was input? If it's the latter, you should be using a string comparison, and you should be using the proper ASCII codes for the character you want to compare. (This is 0x30 or '1'' for 1 .) A string comparison stops as soon as one of the strings is a NUL ( '\\0'`), meaning you don't compare meaningless padding if any exists.

char *input = GetInput();
if (strcmp(input, "1234") == 0) { ... }

your characters will resolve to ASCII values so you should specify it as:

 char Sequence[]={'1','2','3','4',0,0};

Or compare against an actual string like:

char Sequence[]="1234";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM