简体   繁体   中英

Nicest syntax to initialise a char array with a string, ignoring the null terminator

I often want to do something like this:

unsigned char urlValid[66] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";

...or:

unsigned char listOfChar[4] = "abcd";

...that is, initialize a character array from a string literal and ignoring the null terminator from that literal. It is very convenient, plus I can do things like sizeof urlValid and get the right answer.

But unfortunately it gives the error initializer-string for array of chars is too long .

Is there a way to either:

  • Turn off errors and warnings for this specific occurrence (ie, if there's no room for null terminator when initialising a char array)
  • Do it better, maintaining convenience and readability?

You tagged your question as both C and C++. In reality in C language you would not receive this error. Instead, the terminating zero simply would not be included into the array. Ie in C it works exactly as you want it to work.

In C++ you will indeed get the error. In C++ you'd probably have to accommodate the terminating zero and remember to subtract 1 from the result of sizeof .

Note also, that as @Daniel Fischer suggested in the comments, you can "decouple" definition from initialization

char urlValid[66]; 
memcpy(urlValid, "ab...", sizeof urlValid);

thus effectively simulating the behavior of C language in C++.

Well, in C++ you should always use std::string . It's convenient and not prone to memory leaks etc.

You can, however, initialize an array without specifying the size:

char urlValid[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";

This works since the compiler can deduce the correct size from the string literal. Another advantage is that you don't have to change the size if the literal changes.

You should not use unsigned char for strings. 您不应该对字符串使用unsigned char

用实际的字符数组初始化吗?

char urlValid[] = {'a','b','c','d','e','f',...};

there are two simple solutions.

  1. You can either add an extra element into the array like this:

     unsigned char urlValid[67] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~"; 
  2. or leave out the size of the array all together:

     unsigned char urlValid[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~"; 

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