2

This came up in another questions comment

String literals have static storage duration (see standard 6.4.5/6). – Jean-Baptiste Yunès

And I didn't want to hijack the comment section for this. So the question is when I do this:

char arr[10] = "Hello";

Do I actually have two strings in my memory? One at arr until my scope ends (auto duration) and one at the point where ever the literal was created until the program closes (static duration)

Would this be equivalent to this:

char* str = "Hello";
char arr[10];
memcpy(arr,str,6);

If this is true, then I want to make sure what happens with char a = 'a';

Does this also have double allocation? I would have guessed 'a' would be written directly to a

Resulting in my last question would this be more memory efficient?

char arr[10] = { 'H', 'e', 'l', 'l', 'o', '\0'}

huysentruitw
  • 27,376
  • 9
  • 90
  • 133
Kami Kaze
  • 2,069
  • 15
  • 27
  • 1
    I think yes. There will be two copies of the string. See this question- http://stackoverflow.com/questions/38146826/returning-string-from-a-c-function – MayurK Oct 19 '16 at 11:58
  • 1
    `char arr[10] = { 'H', 'a', 'l', 'l', 'o', '\0'}` and `char arr[10] = "Hello";` are strictly the same thing. – Jabberwocky Oct 19 '16 at 12:00
  • @MichaelWalz thank your for clarifying that and I got the answer to the first part of the question as well. Last question is does `'a'` use additional storage besides `a`? – Kami Kaze Oct 19 '16 at 12:12
  • 1
    `char a = 'a';` is the same thing as `char a; ...; a = 'a';`, so your thoughts are correct `'a'` is simply written to `a`. – Jabberwocky Oct 19 '16 at 12:25

0 Answers0