0

I need to write c program to compare two strings without using strncpy() and then in another funtion check whether it works with using assert()

In my code by checking with pointers assert(*str2 == *"comp"); I only check the first letter and nothing else.So even there is another word starting with c, it will work.

char initialize_n(char str1[], char str2_n[], int n)
{
    //initialize a string from the (at most) n first characters of another string
    int i = 0;
    for(i = 0; i < n; i++)
    {
        str2_n[i] = str1[i];
    }
    str2_n[i] = '\0'; 
}
void test_initialize_n(){
    char str1[100] = "computer";
    char str2[100];
    initialize_n(str1, str2, 4);
    assert(*str2 == *"comp");
}

How to correctly check it with assert?

Narm
  • 1

1 Answers1

0

So, without gcc extensions you can't put this into the assert body because the functions that would do so are forbidden to you.

What you need to do is write your own compare function and call it. Skeleton as follows:

int prefix_equals(const char *left, const char *right, int nleft, int nright)
{
    if (nleft != nright) return 0;
    /* Use the same for loop here you have in initialize_n */
        if (left[i] != right[i]) return 0;
    return 1; /* If you got all the way through they're equal */
}

    assert(prefix_equals(str2, "comp", 4, 4));

In my experience the most useful form of this actually has two length arguments to save the caller from some ugliness in the call point. It seems wrong at assert level but it isn't wrong when you get to a few thousand lines.

Joshua
  • 40,822
  • 8
  • 72
  • 132