简体   繁体   中英

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

#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]

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;
}

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.

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';

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