How to put double-digit char like '51' in a char array?

4.9k views Asked by At
#include<stdio.h>


int main(){
char array[3][3]={{'2','1','3'},{'4','5','9'}};
array[0][0]='51';

}

Error warning: multi-character character constant [-Wmultichar] array[0][0]='51'; ^~~~ 17.4.c:6:17: warning: overflow in implicit constant conversion [-Woverflow]

3

There are 3 answers

0
Artūras Jonkus On

Char can only hold one symbol. '51' is two symbols. It could be three if you would write it between double brackets ("51") because C-type strings are always finished with \0. To hold more than one symbol you should use char pointers and double brackets or access them differently using one dimension:

char* array[3] = {"one", "two", "three"}; 
char string[3][7] = {"one", "two", "three"};

The second line tells that 3 string containing at most 7 characters (including \0) can be used. I've chose such a number because "three" consists of 6 symbols.

0
SergeyA On

If you want to use multi-character constants, you gave to store them in integral variables larger than chars. For example, this works - in a certain way, meaning, it stores a multi-character:

int x = '52';
1
0___________ On

If you want to store two decimal digits in one char you can actually use 4 bit nibbles to store the digits

int two_to_one(const char *number)
{
    return *number - '0' + ((*(number + 1) - '0') << 4);
}

char *char one_to_two(int ch, char *buff)
{
    buff[1] = ch >> 4;
    buff[0] = ch & 0xf;
    buff[2] = 0;

    return buff;
}