简体   繁体   中英

Compare a String with a Char in C

I'm having an issue with this:

char procNames[10][80];

[...]

strncpy(procNames[i], readedLineFromBuffer, 80);

On readedLineFromBuffer only enters one char.

Then I want to compare another char that I input by stdin with the chars that I stored in procNames.

So, for example, I have:

procNames[0]: A
procNames[1]: B
procNames[2]: C

And, by stdin buffer (named line in my program) I write IS B INSIDE or IS C INSIDE , IS <CHARACTER> INSIDE ...

So I get line[3] , that will be the B or C character, and I want to check if line[3] is stored in procNames.

I do the following:

for(int strgName = 0; strgName < processNumber; strgName++) {
    if(strncmp(line[3], procNames[strgName], 1) == 0) {
        fprintf(stdout, "MATCH: %s\n", strgName, procNames[strgName]);
        isInsideProgram = true;
    }
} 

But the strncmp() throws segfault. How do I compare what is inside procnames[10][80] (that is a character) with line[3] ? I've tried with strcmp() and line[3] == procNames[strgName] but it throws segfault too...

Edit: It was solved by comparing line[3] == procNames[strgName][0] thx a lot!

line[3] is a char , but the first two arguments to strncmp() must be char * . You could use &line[3] .

But simpler is to just compare the characters directly:

if (line[3] == procNames[strgName][0])

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