简体   繁体   中英

how to cast a char array to compare it with unsigned char array?

I am trying to cast s2 to make the test pass.

I store printable characters together with unsigned char values into s3.

s2 is a test string result meant to verify printable char are loaded properly in s3.

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

#define test_string_len 2

union {
    char unsigned us[test_string_len];
    char          s1[test_string_len];  
} result;

main() {

    char *s2;
    s2=  "ab";         

    char unsigned s3[test_string_len];          
    s3[0] = 'a';
    s3[1] = 'b';    
    s3[2] = '\0';   

    memcpy (result.us, s3, test_string_len);                

    if ( result.s1 == s2)    {

            printf("Pass\n");
    }

    printf("s2 = %s\n", s2 );
    printf("s3 = %s\n", s3 );   
    printf("result.s1 = %s\n", s3 );
    printf("result.us = %s\n", result.us );

    getchar();
}

It's not possible to compare strings (or other arrays) with == in C. This is because an array such as int myarray[8]; can essentially be thought of as a pointer called myarray storing the address of the first element. In other words, == would compare the starting address of the array, rather than the contents of the actual array items being pointed to.

Instead, you must either use the strcmp or memcmp functions, or use a for() loop to cycle through each index and check that the values in each array match.

You need to change your code as follows.

 if(!strcmp( result.s1,s2))    {

            printf("Pass\n");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM