Question about odd syntax: char* c = {"Text"};
Hi,
I have run across the some strange syntax, to which I do not
understand the meaning:
const char* xmlHeader = {"<?xml"};
(specifically, this can be found in "tinyxmlparse.cpp", Line 828, from
the "tinyxml" project on Sourceforge at
<http://sourceforge.net/projects/tinyxml/>). I should note that this
does compile with gcc v4.0.1.
Originally, I thought this syntax would only make sense if we were
dealing with char*[] or char**. My second interpretation was that this
notation essentially dynamically allocates an array of chars,
initialized with "<?xml". However, this does not seem to hold, based on
the following test.
#include <iostream>
using namespace std;
int main ()
{
const char* a = "Test 1 has address ";
char* b = new char[12];
const char* c = {"Test 3 has address "};
char d[] = "Test 4 has address ";
char e[12];
cout << "a: " << a << ((const void *) a) << endl;
cout << "b: Test 2 has address " << ((const void *) b) << endl;
cout << "c: " << c << ((const void *) c) << endl;
cout << "d: " << c << ((const void *) d) << endl;
cout << "e: Test 5 has address " << ((const void *) e) << endl;
// delete [] c;
// delete c;
}
In my particular instance, I get
a: Test 1 has address 0x2eb0
b: Test 2 has address 0x500150
c: Test 3 has address 0x2ec4
d: Test 3 has address 0xbfffed84
e: Test 5 has address 0xbfffed98
This implies to me that the {}s do not actually do anything, as both a
and c do not appear to be pointing at something on the heap (like d and
e) or on the stack (like b). That can be further supported by
uncommenting either one of the delete's at the end, which gives me
malloc: *** Deallocation of a pointer not malloced: 0x2ec4; This
could be a double free(), or free() called with the middle of an
allocated block; Try setting environment variable MallocHelp to see
tools to help debug
My question is, does this notation actually serve any purpose? And while
I am at it, is there any nice notation to do in one statement what I
thought this did, i.e. something like
char temp_literal[] = "<?xml";
char* temp_pointer = new char[strlen (temp_literal)]";
strcpy (temp_pointer, temp_literal);
const char* c = temp_pointer;
Thank you for any help,
Bruce