c - 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.
解决方案
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
推荐阅读
- jquery - 如何统一 jQuery 图片脚本?
- c - 为什么我的地区问题给出了错误的答案?
- laravel - 在 Laravel 中向路由传递三个以上的参数
- typescript - 来自 TypeScript 的 Redux Action Creator 函数参数的误报?
- r - 如何在保留列名的同时将矩阵的列巧妙地列出到数据框中?
- java - Hibernate 无法从数据库中获取 SequenceInformation
- go - time.Duration 之间的绝对差异
- r - 在 R 中添加具有现有输出的重要星行
- reactjs - 当我使用带有 typescript 的 create-react starter 时,如何只创建一个 bundle js 文件?
- python - 如何用混合信号的主频率解释图形?