Why can’t I initialize a local array with a string
+6
A:
Why can’t I initialize a local array with a string
The correct answer is that you can – for a given definition of array, and string. What exactly do you want to achieve?
char str[] = "Hello world";
Konrad Rudolph
2009-06-25 07:27:28
this would better be "const char str[]". Otherwise you may end up writing into the executable bytes.
xtofl
2009-06-25 08:11:37
@xtofl: No. In the above code, the constant string literal is *copied* into a writable memory location. The code is safe and `str` may safely be manipulated. You would be right if I had used a pointer instead of an array.
Konrad Rudolph
2009-06-25 09:19:32
+3
A:
The question is very skinny on details but:
char arr[] = {'a','b','c', 0};
or
char arr[] = "string";
EDIT:
In response to questions:
char s1[] = "hi";
char s2[] = {'h','i',0};
memcpy(s1, "by", sizeof(s1));
memcpy(s2, "by", sizeof(s2));
cout << ios::hex << &s1 << endl;
cout << ios::hex << &s2 << endl;
cout << s1 << endl;
cout << s2 << endl;
Prints:
80xbfffed72
80xbfffed6f
by
by
At least on my system it looks like both are allocated in the same memory space, I don't see any problems or differences. C for example defines string
as a null terminated char array - I believe this is the same in C++, not to be confused with std::string
.
stefanB
2009-06-25 07:28:15
These are not equivalent: the latter form allows you to e.g. memset( arr, 0, 7), and thus change your executable's data segment.
xtofl
2009-06-25 08:13:04
@xtofl: Can you go into that in more detail? I'm pretty sure that both of these are equivalent. It would be different if the second was "const char * arr=", but it isn't, and I'm pretty sure that a quoted string is just a special syntax for an aggregate initializer, and so the behaviour should be identical.
Richard Corden
2009-06-25 09:46:02
+1
A:
std::vector<std::string> abc(5,"abc");
will create a vector with 5 elements initialized to "abc".
Totonga
2009-06-25 07:33:35