Home > Software engineering >  Array of pointers to char in C
Array of pointers to char in C

Time:03-07

I am confused with how an array of pointer to char works in C.

Here is a sample of the code which I am using to understand the array of pointers to char.

int main() {
    char *d[]={"hi","bye"};
    int a;
    a = (d[0]=="hi") ? 1:0;
    printf("%d\n",a);
    return 0;
}

I am getting a = 1 so d[0]="hi". What is confusing me that since d is an array of char pointers, shouldn't be a[0] equal to the address of h of the hi string ?

CodePudding user response:

C 2018 6.4.5 specifies the behavior of string literals. Paragraph 6 specifies that a string literal in source code causes the creation of an array of characters. When an array is used in an expression other than as the operand of sizeof, the operand of unary &, or as a string literal used to initialize an array, it is automatically converted to a pointer to its first character. So char *d[]={"hi","bye"}; initializes d[0] and d[1] to point to the first characters of "hi" and "bye", and d[0]=="hi" compares d[0] to a pointer to the first character of another "hi".

Paragraph 7 says that the same array may be used for identical string literals:

It is unspecified whether these arrays are distinct provided their elements have the appropriate values…

Thus, when your compiler is taking the address of the first element of "hi" in d[0]=="hi", it may, but is not required to, use the same memory for "hi" as it did when initializing d[0] in char *d[]={"hi","bye"};.

(Note that the paragraph also allows the same memory to be used for string literals identical to the substrings at the ends of other string literals. For example, "phi" and "hi" could share memory.)

  • Related