3

While playing around I found a result I cannot get my head around, which involves char arrays and pointer.

char charArray[] = "Array";
char* charPtr1 = "Array";
char* charPtr2 = "Array";

why is charArray != charPtr1/2, but charPtr 1 == charPtr2?

I though when creating charPtr1, it would create a temp array and point to there. If that's the case, why aren't they the same?

Achal
  • 11,821
  • 2
  • 15
  • 37
MrEmper
  • 225
  • 1
  • 4
  • 18
  • "it would create a [_different_] temp array" – ForceBru Apr 23 '19 at 18:48
  • There is a single constant "Array" that both charPtr1 and charPtr2 are referencing, but charArray declares it's own storage, so *charArray points at a different location. You can think of it as: the constant "Array" is copied into the storage allocated for charArray[]. I don't know if sharing constant strings is defined in the C standard or is compiler-specific. If you want charPtr1 and charPtr2 to point to the same thing as charArray, then declare them as: char * charPtr1 = charArray; – Alcamtar Apr 23 '19 at 18:54

3 Answers3

4
char charArray[] = "Array";
char* charPtr1 = "Array";
char* charPtr2 = "Array";

why is charArray != charPtr1/2, but charPtr 1 == charPtr2?

charArray is in fact char charArray[6] = { 'A', 'r', 'r', 'a', 'y', 0 };, so it is an array, whose contains can be changed

charPtr1 and charPtr2 are pointer to a char so none of them can be equal to charArray (except after charPtr1 = charArray; etc of course)

The fact charPtr1 and charPtr2 is an optimization of the compiler, that one detect the literal string "Array" is used several times, defines it one time and use its address to initialize the two variables

Community
  • 1
  • 1
bruno
  • 32,421
  • 7
  • 25
  • 37
4

This might help.

A disassembly of

char charArray1[] = "Array";
char* charPtr1 = "Array";
char* charPtr2 = "Array";

with GCC8.3 shows

charArray1:
        .string "Array"
.LC0:
        .string "Array"
charPtr1:
        .quad   .LC0
charPtr2:
        .quad   .LC0

In other words, the two pointers point to the same memory location containing the string "Array", while the array holds its own copy of the string.

As the link suggests, the memory for the char array is separated like that due to the different types in question. Regarding the pointers, because their job is to just point to some data, probably the compiler chooses to optimize out duplicated allocations for the same literal data.

The literal data for the pointers is read-only.

afp
  • 103
  • 7
1

The first char charArray[] = "Array"; is equivalent to char charArray[] = {'A', 'r', 'r', 'a', 'y', '\0'} which is an initialization of the array object with automatic storage duration.

The cases 2, 3 both points to the first element of the same array object meaning the pointers compare equal. The standard specifies that 6.5.2.5(p7):

String literals, and compound literals with const-qualified types, need not designate distinct objects

Some Name
  • 8,555
  • 5
  • 27
  • 77