Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C String Literal "too big for character"

Tags:

c

string

literals

With MSVC 2010 i try to compile this in C or C++ mode (needs to be compilable in both) and it does not work. Why? I thought and found in the documentation that '\x' takes the next two characters as hex characters and not more (4 characters when using \X").

I also learned that there is no portable way to use character codes outside ASCII in C source code anyway, so how can i specify some german ISO-8859-1 characters?

int main() {
     char* x = "\xBCd";  // Why is this not char(188) + 'd'
}

// returns  test.c(2) : error C2022: '3021' : too big for character
// and a warning with GCC
like image 448
Lothar Avatar asked Dec 03 '12 21:12

Lothar


People also ask

How do you declare a wide character in string literal?

A wide string literal is a null-terminated array of constant wchar_t that is prefixed by ' L ' and contains any graphic character except the double quotation mark ( " ), backslash ( \ ), or newline character. A wide string literal may contain the escape sequences listed above and any universal character name.

Why can't you modify a string literal C?

Modifying a string literal frequently results in an access violation because string literals are typically stored in read-only memory. (See undefined behavior 33.) Avoid assigning a string literal to a pointer to non- const or casting a string literal to a pointer to non- const .

What is the size of string literal?

While an individual quoted string cannot be longer than 2048 bytes, a string literal of roughly 65535 bytes can be constructed by concatenating strings.

Can you change the length of a string in C?

Short answer is no. Somewhat longer answer: these strings have a limited length and you can't expand them.


1 Answers

Unfortunately you've stumbled upon the fact that \x will read every last character that appears to be hex1,2, instead you'll need to break this up:

const char *x = "\xBC" "d"; /* const added to satisfy literal assignment probs */

Consider the output from this program:

/* wide.c */
#include <stdio.h>
int main(int argc, char **argv) 
{
    const char *x = "\x000000000000021";
    return printf("%s\n", x);
}

Compiled and executed:

C:\temp>cl /nologo wide.c
wide.c

C:\temp>wide
!
  1. Tested on Microsoft's C++ compiler shipped with VS 2k12, 2k10, 2k8, and 2k5
  2. Tested on gcc 4.3.4.
like image 139
user7116 Avatar answered Sep 28 '22 02:09

user7116