I have the code below, and I'm trying to compare the content of arrayx
with argv[2]
(user input argument upon execution), however even when the argv[2]
matches with the content of arrayx
, it bypasses to the else statement.
If I try to use:
strcpy(arg3, "inputstring" );
Then it works.
Also, if I try to printf(%s, arrayx)
, it prints out the correct string.
Any idea why it does not work when I try to use the arrayx variable on strcmp ?
float float_arrayx[] = {
0x69, 0x6e, 0x70, 0x75, 0x74, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x0a
};
unsigned char arrayx[sizeof(float_arrayx) / sizeof(*float_arrayx)];
for (size_t j = 0; j < sizeof(arrayx) / sizeof(*arrayx); j ) {
arrayx[j] = (unsigned char)float_arrayx[j];
}
if (argc == 3 && (strcmp(argv[1], arg_help))) {
char arg3[100];
char arg2[32];
strcpy(arg3, arrayx );
strcpy(arg2, "-exec");
if(!strcmp(argv[1], arg2)) {
if(!strcmp(argv[2], arg3))
{
printf("\nDO SOMETHING....\n");
CodePudding user response:
arrayx
has the length of the float array, so it has one character space for every item in the array. But C strings are null-terminated (the last char must be \0
), so if you want to use them with the standard string library functions, you need to get arrayx
null-terminated. That means its size will need to be 1 greater. I'm not sure if you need to manually set the last space to zero, so I would just in case:
unsigned char arrayx[sizeof(float_arrayx) / sizeof(*float_arrayx) 1];
for (size_t j = 0; j < sizeof(float_arrayx) / sizeof(*float_arrayx); j ) {
arrayx[j] = (unsigned char)float_arrayx[j];
}
arrayx[sizeof(float_arrayx) / sizeof(*float_arrayx) 1] = 0;
I'm also not familiar with arg_help
so I'm not sure if this will fix your problem, but it should be a start.
CodePudding user response:
Taking no responsibility for the rest of the code, there's this...
To circumvent the "terminating null" problem, perhaps one could use
// You use sizeof for filling char array
size_t lenPswd = sizeof arrayx/sizeof arrayx[0];
// Use sizeof for comparing bytes, not two strings
if( strncmp( argv[2], arrayx, lenPswd ) == 0 )
Write code for clarity, not for density... The compiler will optimise as it does, but the reader shouldn't be expected to "notice" and parse the meaning of "!" applied to the return value. Be clear...