0

I'm trying to compare two string arrays. I write a method which called compare this method compare two string arrays and if it find same element in this arrays it stores that string in "intersect" array which compare method will be return. But even thought this two array has same elements when I try to print f which I try to equalize "intersect" array it prints empty array. How to I fix it, could yo please help me?

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

char *compare ( char *course1[], char *course2[]);

int main()
{
char a1 [12][50] = {"10000000000","10000000010","20000000010","30000000030","30000000010","40000000010","50000000010","50000000020","60000000020","70000000010"};
char a2 [12][50] = {"70000000010","10000000000","60000000020","11000000010","31000000030","31000000010","80000000010","50000000010"};
char *f = compare(*a1,*a2);

for(int b=0;b<sizeof(*f);b++){
    printf("%c\n",f[b]);
}

return 0;
}

char *compare ( char *course1[], char *course2[]){
static char intersect[12][500];
    int i = 0;
    int k = 0;
 while(i<sizeof(*course1)){
     int j = 0;
     while(j<sizeof(*course2)){
       int cmp = strcmp(course1[i],course2[j]);
       if(cmp==0){
          strcpy(intersect[k],course1[i]);
           k++;
           j++;
       }
       else{
           j++;
       }
    }
    i++;
}
 
 return *intersect;
}
sena
  • 1
  • 3
    note: `sizeof(*course1)` is most likely 8 – user253751 May 20 '22 at 10:35
  • As @user253751 mentioned sizeof(*course1) is not the best approach. As it won't work. You have the information about the size of the passed arrays also inside of your function as a magic numbers. So, instead of calculating the size of your arrays by using sizeof you could just iterate over the 12 and 500. But maybe you create static variables for them. Or pass them as parameters. – lghh May 20 '22 at 11:43

0 Answers0