首页 > 解决方案 > structure initialization failed

问题描述

 int main()
{
    int i;
    typedef struct {
        int no[6];
        int socket;
    }data;

    data  *a = {
        a->no[6] = {0},
        a->socket= 3,
    };

    printf( "no[0] = %d\n",a->no[0]);
    printf("socket  = %d\n", a->socket);

    getchar();
    return 0;
}

In this simple code, I have created a structure and initializing it using structure pointer - assigning 0 value to all elements of array 'no' and value 3 to variable socket. I am getting error as : error C2440: 'initializing': cannot convert from 'initializer list' to 'data *' note: The initializer contains too many elements

where am I going wrong? I also tried with

    data  a = {
        a.no[6] = {0},
        a.socket= 3,
    };
  printf("no0 = %d\n",a.no[0]);
    printf("socket  = %d\n", a.socket);

here the code is running but showing a.socket = 0 instead of 3.

标签: cstructinitializationdeclaration

解决方案


This declaration

data  *a = {
    a->no[6] = {0},
    a->socket= 3,
};

does not make sense. If you want to declare a pointer to the structure then you could use either a compound literal like

data *a = ( data[] ){ { { 0 }, 3 } };

or should allocate dynamically an object of the type data.

data *a = malloc( sizeof( data ) );
a->no[0] = 0;
a->socket = 3;

If you do not want to declare a pointer then you can write the following way as it is shown in the demonstrative program

#include <stdio.h>

typedef struct {
    int no[6];
    int socket;
} data;

int main(void) 
{
    data a = { { [0] = 0 } , .socket = 3 };
    printf( "no0 = %d\n",a.no[0] );
    printf("socket  = %d\n", a.socket);

    return 0;
}

The program output is

no0 = 0
socket  = 3

推荐阅读