Search code examples
cstrcmp

in C the correct way to test nth character == "x" in a string passed to a function


Given the following I am getting a segmentation fault and I am not sure if it is because I am testing against a pointer or other issue.

What is the correct way to test if the 4th character is a comma?

string is read from fifo abc,def,xyz

char in[BUFFER] = {'\0'};
if ((in_fl = open(*fifofile, O_RDONLY)) == -1)
    {
     while (read(in_fl, in, BUFFER)>0) {
      doParseInput(&in);
    }


void *doParseInput(char *inputread){
//copy string to use later....
 char* theParsedString = calloc(strlen(inputread)+1, sizeof(char));
 strcpy(theParsedString , inputread);
 if (strcmp(theParsedString[3], ",") == 0){ //causes seg fault

I have also tried using the passed string directly, but also seg fault

if (strcmp(inputread[3], ",") == 0){ //causes seg fault

Solution

  • To pass a buffer to a function, don't use &.
    Instead:

    doParseInput(in);
    

    To compare the 4th character of a buffer (index == 3):

    if (theParsedString[3] == ','){ 
    

    (Notice the single-quotes, meaning Character-Value, rather than the double-quotes, which would mean "String")