Search code examples
carraysloopscomparisonc-strings

How to compare char and char * in C


I'm not sure why this isn't working, it doesn't print anything. csvArry has 3 elements in it and capList has 4 elements. I want to search capList to see if there is an element in it that matches an element in csvArray.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>



int main(int argc, char *argv[]) {


    char *csvArray[] = {"1000", "CAP_SYS_ADMIN", "CAP_SYS_RAW"};
    char *capList[] = {"CAP_SYS_SETFCAP", "CAP_SYS_SETPCAP", "CAP_SYS_ADMIN", "CAP_SYS_RAW"};

    int i = 0;
    int j;
    while(i<3){
          for(j=0;j<4;j++){
              if(strcmp(csvArray[i],capList[j]) == 0){
                        printf("Match");
              }
          }
          i++;
    }

  return 0;
}



Solution

  • There you go:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main(int argc, char *argv[])
    {
    
        char *csvArray[] = {"1000", "CAP_SYS_ADMIN", "CAP_SYS_RAW"};
        char *capList[] = {"CAP_SYS_SETFCAP", "CAP_SYS_SETPCAP", "CAP_SYS_ADMIN", "CAP_SYS_RAW"};
    
        int size = sizeof(csvArray) / sizeof(csvArray[0]);
        int sizeOfList = sizeof(capList) / sizeof(capList[0]);
    
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < sizeOfList; j++) {
                if (strcmp(csvArray[i], capList[j]) == 0) {
                    printf("%s Match\n", csvArray[i]);
                }
            }
        }
    
        return 0;
    }
    

    This program tries to find which elements are common to both and it prints which are common too.

    Output

    CAP_SYS_ADMIN Match
    CAP_SYS_RAW Match