I actually need to process an array of strings
What you have defined here
char str[] = {'1', '45', '0'};
is not an array of strings, but exactly one array of char
with 3 elements. It is not even a C-"string", as this would require a trailing value of 0
. Note that the value of the character '0'
isn't 0
, but, for example, for the ASCII character set it's 48
.
'45'
is a multi-byte character literal, which in fact is an integer. The code above tries to initialise the 2nd element of the char
-array str
(str[1]
, which is a char
) using this very literal.
This does not work.
A char
cannot (necessarily) hold the int
value of this multi-byte character literal. In this case the initialisation of str[1]
overflows, resulting in the unexpected value of 5
.
To see the issue try the following code:
#include <limits.h>
#include <stdio.h>
int main(void)
{
char c_min = CHAR_MIN;
char c_max = CHAR_MAX;
unsigned char uc = '45';
printf("'1'=%d\n", '1');
printf("'45'=%d\n", '45');
printf("'0'=%d\n", '0');
printf("lowest possible value for char=%d\n", c_min);
printf("highest possible value for char=%d\n", c_max);
printf("'45' converted to an (unsigned) char=%u\n", uc);
return 0;
}
The example above shows how the value of 45
gets truncated when being assigned to char
.
Depending on the C implementation you use the conversion of '45'
to a char
might even invoke the infamous Undefined Behaviour. This is not good.
What you seem to be wanting is:
#define ARRAY_SIZE_MAX 3
char * str[ARRAY_SIZE_MAX] = {"1", "45", "0"}; /*. Mind the double quotes. */
This defines an array of 3 pointers to char
, with each pointing to a C-"string".