I am trying to compare strings received from the command line arguments without using the string library. I have created a function to compare char*'s and it works for strings I create in my program, but not on strings passed in the command line. Here is the code for reference.
#include <stdio.h>
int comparestr(char* a, char* b) {
printf("string 1 = %s, string 2 = %s\n", a, b);
int len_a =0, len_b=0;
while(*a) {
len_a++;
a++;
}
while(*b) {
len_b++;
b++;
}
printf("len a = %d, len b = %d\n", len_a, len_b);
if (len_a == len_b) {
for(int i=0; i<len_a; i++) {
if(*(a+i) != *(b+i)) {
return 0;
}
}
return 1;
}
else
return 0;
}
int main(int argc, char**argv) {
char* str1 = "hello";
char* str2 = "hello";
if(comparestr(str1,str2))
printf("Same string.\n");
else
printf("Different strings.\n");
if(comparestr(*(argv+1),"hell"))
printf("Same cl string.\n");
else
printf("Different cl strings.\n");
return 0;
}
Here is an example of the output.
./a.out hell hell
string 1 = hello, string 2 = hello
len a = 5, len b = 5
Same string.
string 1 = hell, string 2 = hell
len a = 4, len b = 4
Different cl strings.
comparestris that it irreversibly modifies its arguments when computing their lengths, and it consequently compares garbage later. Just use standard functions fromstring.hinstead of re-inventing the wheel badly.aandbpointers bylen_aandlen_brespectively after calculating the length so it could go back to its original starting point and it worked. When you calculate the length, you actually bringaandbpointers to the NULL terminators, so the comparison is all undefined behavior from then on.*(a+i). Instead, writea[i], which is equivalent and much clearer.ais the string"hello"andbhas a billion characters, starting withhello. It's only necessary to look at 12 characters to render a judgement. But your code examines 1,000,000,007 characters.