Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
C++
const char* = new char[6]
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="Frederick Gotham, post: 2580757"] S S posted: String Literals have static storage duration. Therefore, it's quite equivalent to: /* Step 1: We have a static duration const array. */ static char const literal_[] = {'H','e','l','l','o',0}; /* Step 2: It's appears non-const even though we're not allowed to modify it. */ char (&literal)[sizeof literal_] = const_cast<char(&)[sizeof literal_]>(literal_); /* Step 3: We store its address in a pointer variable. */ char const *p = literal; C++ is broken in the respect that you can't individually initialise individual array elements (...well you can, but it involves a work-around involving placement new). Anywho, simple assignment will suffice in the case of POD's: char *const p = new char[6]; p[0] = 'H'; p[1] = 'e'; p[2] = 'l'; p[3] = 'l'; p[4] = 'o'; p[5] = 0; delete [] p; The behaviour of altering const data is not defined by the International C++ Standard. In compiling that code, any conforming compiler is entitled to produce a program which does absolutely anything (and yes, I mean _anything_). Syntax error -- it sort of looks like a definition, except there's no name for the object. Anywho, if you want a non-const char array which contains a null-terminated string at the point of initialisation, then maybe play around with: char str[] = "Hello"; Don't be fooled by the syntax -- the thing on the left is NOT a string literal, it's just a pretty way of writing: char str[] = {'H','e','l','l','o',0}; [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
C++
const char* = new char[6]
Top