0

Writing a string literal is equivalent to writing a pointer to the first character of the string. For example, when we are doing like this ...

char a[]="hello world";

... here "hello world" is a string literal which is equivalent to pointer to 'h'. Then, we are initializing a pointer to the array. How could we do like that? Can we initialize a pointer to an array ?

sind
  • 41
  • 4
  • 2
    These two cases are handled quite differently. When used to initialize an array of unspecified size, the string literal determines the size of the array, and also specifies the initial values of the array elements. The actual string literal does not need to be instantiated in this case. When used to initialize a pointer, then the string literal needs to be instantiated, and its address is used to initialize the pointer. – Tom Karzes Jun 29 '21 at 10:46
  • 3
    What exactly is the question here ? – Sorenp Jun 29 '21 at 10:48
  • My question is how could we initialize a pointer to an array ? – sind Jun 29 '21 at 10:57
  • 1
    @sind I would do `char arr[] = "Hello"; char (*pa)[6] = &arr;`. But I doubt that's what you want. (The `pa` I have here is a true pointer-to-array, which is an obscure and almost useless type in C.) – Steve Summit Jun 29 '21 at 11:00
  • 1
    Note that when you write `char a[] = "hello world";`, you have a *string literal* used as an *initializer*. There are no pointers involved here at all. – Steve Summit Jun 29 '21 at 11:02
  • @Steve Summit I understood it now – sind Jun 29 '21 at 11:03
  • `char a[]="hello world"` does **not** initialize a pointer to an array. It defines an array named `a` of length 12 (11 characters inside the string plus the terminating null character) and initializes it using the array of characters defined by the string literal. When a string literal is used to initialize an array like this, it is **not** converted to a pointer to its first element, by C 2018 6.3.2.1 3. The array defined by the string literal is used for its contents, not as a pointer. – Eric Postpischil Jun 29 '21 at 11:04

0 Answers0