top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

C: What is the difference between memory comparison and string comparison ?

0 votes
552 views

Are both comparisons same or different ?

posted Jul 15, 2017 by Vikram Singh

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Memory Comparison

In the C Programming Language, the memcmp function returns a negative, zero, or positive integer depending on whether the first n characters of the object pointed to by s1 are less than, equal to, or greater than the first n characters of the object pointed to by s2.
Syntax: int memcmp(const void *s1, const void *s2, size_t n);

memcmp Example

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

int main(int argc, const char * argv[])
{
    /* Create a place to store our results */
    int result;

    /* Create two arrays to hold our data */
    char example1[50];
    char example2[50];

    /* Copy two strings into our data arrays
     (These can be any data and do not have to be strings) */
    strcpy(example1, "C memcmp at TechOnTheNet.com");
    strcpy(example2, "C memcmp is a memory compare function");

    /* Compare the two strings provided up to the first 9 characters */
    result = memcmp(example1, example2, 9);

    /* If the two arrays are the same say so */
    if (result == 0) printf("Arrays are the same\n");

    /* Compare the two strings provided up to the first 10 characters */
    result = memcmp(example1, example2, 10);

    /* If the first array is less than the second say so
     (This is because the 'a' in the word 'at' is less than
     the 'i' in the word 'is' */
    if (result < 0) printf("Second array is less than the first\n");

    return 0;
}

string comparison:

The == (double equals) returns true, if the variable reference points to the same object in memory. This is called “shallow comparison”.

The equals() method calls the user implemented equals() method, which compares the object attribute values. The equals() method provides “deep comparison” by checking if two objects are logically equal as opposed to the shallow comparison provided by the operator ==.

If equals() method does not exist in a user supplied class then the inherited Object class's equals() method will be called which evaluates if the references point to the same object in memory. In this case, the object.equals() works just like the "==" operator.

answer Jul 15, 2017 by Ajay Kumar
...