Search code examples
carrayscompressionunsigned-char

Comparing non null-terminated char arrays


I have a compressed unsigned char array of a known size. Due to compression considiration I don't store the null-terminator at the end. I want to compare it to another array of the same format. What would be the best way to do so?

I thought duplicating the comparessed arrays to a new array, add the null-terminator, and then compare them using strcmp().

Any better suggestions?


Solution

  • you can use strncmp() function from string.h

    strncmp(str1, str2, size_of_your_string); 
    

    Here you can manually give the size of string(or the number of characters that you want to compare). strlen() may not work to get the length of your string because your strings are not terminated with the NUL character.

    UPDATE:

    see the code for comparison of unsigned char array

    #include<stdio.h>
    #include<string.h>
    main()
    {
    
    unsigned char str[]="gangadhar", str1[]="ganga";
    if(!strncmp(str,str1,5))
    printf("first five charcters of str and str1 are same\n");
    else
    printf("Not same\n");
    
    }