3

I'm trying to initialize an struct array using designated initializer:

A[size].from = {[0 ... size - 1] = 0};
A[size].to = {[0 ... size - 1] = 0};

List.h:

typedef struct Buffer
{
    int from;
    int to;
}buffer_t;
typedef struct shared_memory
{
buffer_t A;
int size;
} share_t

Main.c

#include <stdio.h>    
#include "list.h"  
buffer_t A[];
int size;
void main(int argc, char *argv[])
{
    share->share_t *share = (share_t *)malloc(sizeof(share_t));
    long arg = strtol(argv[1], NULL, 10);
    size = arg;
    share->A[size] = {[0 ... size-1] = 0};
}

However this is the following error I'm receiving:

enter image description here

I'm using MinGW gcc and command prompt to compile this code and I'm writing this code in Visual studio.

Community
  • 1
  • 1
Zam-Oxy
  • 130
  • 10
  • Welcome to SO. Please post more code showing the definition of `A`, `size`, etc. – rtx13 Apr 30 '20 at 04:04
  • I've uploaded more code, while doing so I found the problem. A[] can only be initialized once. But I can initialize it without size input from user. – Zam-Oxy Apr 30 '20 at 04:10
  • the edited code contains a lot of errors, please post your actual code and explain what you are trying to achieve with the initializer – M.M Apr 30 '20 at 04:10
  • You cannot have `buffer_t A[];` without size, the size must be known in an array declaration – M.M Apr 30 '20 at 04:16
  • But size must be declared by user input in command prompt. – Zam-Oxy Apr 30 '20 at 04:17
  • also can you explain the purpose of this "initializer" ? are you trying to set the array contents to zeroes? – M.M Apr 30 '20 at 04:28
  • Yes, they all must start at zero and will gather information from other functions. – Zam-Oxy Apr 30 '20 at 04:29
  • Please do not show text messages as graphics. Especially not if one has to follow some link to see them. (But also not directly in the question itself, please) Just copy&paste them into the question. – Gerhardh Apr 30 '20 at 05:54

1 Answers1

3

Your code is an assignment expression, not an initializer. Initialization can only happen when an object is defined.

Also, arrays must be defined with a size. And there are better ways to zero-initialize an object than to attempt to use designated initializer ranges.

Here are two options:

int main(int argc, char *argv[])
{
    long size = strtol(argv[1], NULL, 10);
    buffer_t A[size];
    memset(&A, 0, sizeof A);

or

buffer_t *A;
size_t size;

int main(int argc, char *argv[])
{
    size = strtol(argv[1], NULL, 10);
    A = calloc(size, sizeof *A);  // already zero-initialized

The latter is probably better in that you can check for allocation failure and it supports large allocations.

M.M
  • 138,810
  • 21
  • 208
  • 365