【问题标题】:Designated Initializer Array in CC中的指定初始化数组
【发布时间】:2020-04-30 03:51:35
【问题描述】:

我正在尝试使用指定的初始化器来初始化结构数组:

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

列表.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};
}

但是,这是我收到的以下错误:

enter image description here

我正在使用 MinGW gcc 和命令提示符编译此代码,我正在 Visual Studio 中编写此代码。

【问题讨论】:

  • 欢迎来到 SO。请发布更多显示Asize等定义的代码。
  • 我上传了更多代码,但在这样做时我发现了问题。 A[] 只能初始化一次。但是我可以在没有用户输入大小的情况下对其进行初始化。
  • 编辑的代码包含很多错误,请发布您的实际代码并说明您尝试使用初始化程序实现的目标
  • buffer_t A[]; 不能没有大小,数组声明中必须知道大小
  • 但大小必须由用户在命令提示符下输入。

标签: c arrays gcc struct designated-initializer


【解决方案1】:

您的代码是赋值表达式,而不是初始化程序。初始化只能在定义对象时发生。

此外,数组必须定义一个大小。还有比尝试使用指定的初始化范围更好的方法来对对象进行零初始化。

这里有两个选项:

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

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

后者可能更好,因为您可以检查分配失败并且它支持大分配。

【讨论】:

  • 我现在得到的 buffer_t 和 void* 的数据类型不兼容。我正在使用 calloc 方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-06
  • 1970-01-01
相关资源
最近更新 更多