1

for the following code I was wondering if there is just an array created in the stack or if there is also an array created in the static. I'm just kind of confused with array creation from a string.

char str[] = "White";

I'm assuming this creates a pointer in the stack called str which points to an array with the following contents, "White\0", in the static memory. Is this correct as an assumption?

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
gndimitro
  • 107
  • 8

2 Answers2

8

Nope.

"White" is an array of char[6] in static memory somewhere. (or magic land, it's not specified, and is completely irrelevant). Note that it may or may not be the same static array as another "White" elsewhere in the code.

char str[] = "White"; creates a new local char[6] array on the stack, named str, and copies the characters from the static array to the local array. There are no pointers involved whatsoever.

Note that this is just about the only case where an array can be copied. In most situations, arrays will not copy like this.

If you want a pointer to the magic static array, simply use const char* str = "White";

Phonetagger notes that if the line of code is not in a function, then str is not on the stack, but also in the magic static memory, but the copy still (theoretically at least) happens just before execution begins of code in that translation unit.

Community
  • 1
  • 1
Mooing Duck
  • 64,318
  • 19
  • 100
  • 158
  • I don't think I've ever seen this question answered so clearly and accurately... and I've seen this question asked _a lot_. – Lightness Races in Orbit Dec 13 '12 at 22:19
  • 2
    Actually, that's not an array copy, but the initialization syntax for `char` arrays. – Matteo Italia Dec 13 '12 at 22:19
  • 2
    @MatteoItalia: The point is that you're copying from wherever the string literal's "array" is being stored, as part of the initialization. The literal _does_ have array type, so Mooing's answer is accurate. – Lightness Races in Orbit Dec 13 '12 at 22:19
  • Since the OP didn't mention the context in which that line occurs, there's another possibility. If `str` is being declared globally, or at file scope, then nothing is created on the stack at all (at least from the perspective of any user function). – phonetagger Dec 13 '12 at 23:17
4

Wrong. What you described is what happens when you write:

const char * str = "White";

Instead,

char str[] = "White";

creates an array on the stack (large enough to hold that string), and initializes it with that text. "Regular" string literals and the initialization syntax for char arrays are unrelated stuff.

(as for the implementation, often the compiler emits code that looks like

char str[SIZE_OF_THE_STRING];
strcpy(str, "White");

but that's an implementation-specific detail)

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299