Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparison of char array and char pointer

Tags:

arrays

c

char

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?

like image 552
MrEmper Avatar asked Aug 31 '26 23:08

MrEmper


2 Answers

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

like image 108
bruno Avatar answered Sep 03 '26 16:09

bruno


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.

like image 27
afp Avatar answered Sep 03 '26 14:09

afp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!