Click here to Skip to main content
16,016,882 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
C++
int main(void)
{
int distance(char a[], char b[])
{
    int len1 =0;
    for(int i=0;a[i]!='\0';++i){
        if(a[i]<'a'||a[i]>'z')
            return -1;
        ++len1;
    }
    int len2 =0;
    for(int i=0;b[i]!='\0';++i){
      if(b[i]<'a'||b[i]>'z')
           return -0;
    }
    if (len1 != len2) return -3;
    int res=0;
    for(int j=1-len1;j<=0;++j)
          if(a[-j]!=b[-j])
              ++res;
    return res;
}
}


What I have tried:

I run the program and it runs but I didn't understand what it actually asked in question
Posted
Updated 29-Apr-23 9:34am
v2
Comments
Richard Deeming 26-Apr-23 11:24am    
If you have a question about your homework assignment - which we can't see, by the way - then talk to your teacher. That's what they're paid for.

Nothing. That code won't even compile, and would do nothing if it did.

C does not support nested functions: your distance function is defined entirely within the body of the main function - which is otherwise empty, so your whole app starts and immediately ends.

I would also recommend that you don't use -0 as a return value: it is system dependant as some machines can interpret -0 as distinct from 0.
 
Share this answer
 
At least my compiler absolutely does not compile this as C code. Even a C++ compiler comments this with "error C2601: "distance": Local function definitions are invalid".
C
int main(void)
{
    int distance(char a[], char b[])
    {
    ...
    }
}

Actually, the function distance should be above main() and should then be called in main() with valid parameters.
C
int main(void)
{
    char a[] = { ... , 0 };
    char b[] = { ... , 0 };
    int x = distance(a, b);
    return 0;
}

The result is either -1, 0 or -3. The value of res is never calculated, because len2 is never incremented.

Presumably all values in the two arrays should also be compared, which is not realized in the code above. I would never recommend the peculiar negative index loop.
C
for (int j = 1 - len1; j <= 0; ++j)
    if (a[-j] != b[-j])
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900