-2

Say I do initialize an array like this:

char a[]="test";

What's the purpose of this? We know that the content might immediately get changed, as it is not allocated, and thus why would someone initialize the array like this?

Pithikos
  • 18,827
  • 15
  • 113
  • 136
  • 1
    What do you mean by "not allocated"? `a` is allocated on stack in this case. – elmo Jan 04 '12 at 11:49
  • What makes you think that `a` is not allocated ??? Your example is equivalent to `char a[5] = "test";` – Paul R Jan 04 '12 at 11:50
  • Read this: it may help you figure it all out: http://stackoverflow.com/questions/1773079/segmentation-fault-with-char-array-and-pointer-in-c-on-linux – Mike Nakis Jan 04 '12 at 12:05

5 Answers5

5

To clarify, this code is wrong for the reasons stated by the OP:

char* a;
strcpy(a, "test");

As noted by other responses, the syntax "char a[] = "test"" does not actually do this. The actual effect is more like this:

char a[5];
strcpy(a, "test");

The first statement allocates a fixed-size static character array on the local stack, and the second initializes the data in it. The size is determined from the length of the string literal. Like all stack variables, the array is automatically deallocated on exiting the function scope.

Chiara Coetzee
  • 4,201
  • 1
  • 24
  • 20
1

The purpose of this is to allocate five bytes on the stack or the static data segment (depending on where this snippet occurs), then set those bytes to the array {'t','e','s','t','\0'}.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
1

This syntax allocates an array of five characters on the stack, equivalent to this:

char a[5] = "test";

The elements of the array are initialized to the characters in the string given as an initializer. The size of the array is determined to fit the size of the initializer.

sth
  • 222,467
  • 53
  • 283
  • 367
1

It is allocated. That code is equivalent to

char a[5]="test";

When you leave the number out, the compiler simply calculates the length of the character-array for you by counting the characters in the literal string. It then adds 1 to the length in order to include the necessary terminating nul '\0'. Hence, the length of the array is 5 while the length of the string is 4.

Aaron McDaid
  • 26,501
  • 9
  • 66
  • 88
0

The array is allocated; its size is inferred from the string literal being used to initialize it (5 chars total).

Had you written

char *a = "test";

then all that would get allocated would be a pointer variable, not an array (the string literal "test" lives in memory such that it's allocated at program startup and held until the program exits).

John Bode
  • 119,563
  • 19
  • 122
  • 198