1

Here is one not-so-common way of initializing the pointer:

int *p = (int[10]){[1]=1};

Here, pointer point to compound literals.

#include <stdio.h>
int main(void)
{
    int *p = (int[10]){[1]=1};
    printf("%d\n", p[1]);
}

Output:

1

This program is compiled and run fine in G++ compiler.

So,

  • Is it the correct way to initializing a pointer to compound literals? or

  • Is it undefined behaviour initialize pointer to compound literals?

msc
  • 33,420
  • 29
  • 119
  • 214
  • You can initialize it by: `int p[10];` and after set `p[1] = 1` (if you to coding cleanly) – YaatSuka Oct 04 '17 at 05:25
  • It is not a "anonymous array element" but a "compound literal" that happens to be an array. Let's ask otherwise: is there *any* way to use a *compound literal* like this without ever converting it to a pointer? No. The only question is the lifetime of the compound literal. – Antti Haapala -- Слава Україні Oct 04 '17 at 05:42
  • "Is it the correct way to initialize pointer?" Depends on what you want to do with it. The code is 100% equivalent to `int arr[10] = {[1]=1}; int* p = arr;`. Either is perfectly fine if you want an array with local scope. – Lundin Oct 04 '17 at 06:26

1 Answers1

2

Yes, it is valid to have a pointer to compound literals. Standard allows this.

n1570-§6.5.2.5 (p8):

EXAMPLE 1 The file scope definition

int *p = (int []){2, 4};

initializes p to point to the first element of an array of two ints, the first having the value two and the second, four. The expressions in this compound literal are required to be constant. The unnamed object has static storage duration.

haccks
  • 104,019
  • 25
  • 176
  • 264