在c

时间:2018-11-13 18:20:06

标签: c

我正在尝试对int变量使用灵活的数组。

下面是我的代码:

struct S2 {
    int foo;
    int bar;
    int stud_roll[];
}s2g;

void test(){
        s2g.stud_roll = {0};
}

int main(){
        test();
        return 0;
}

但是它不起作用。

如何解决该问题?我的错误是什么?

2 个答案:

答案 0 :(得分:3)

为了将结构体与灵活数组成员(FAM)一起使用,您需要指向结构体的指针,而不是键入struct。 FAM提供了方便,允许在单个分配中分配结构和FAM,而不需要分别分配结构和Microsoft.AspNetCore.App。例如:

stud_roll

在那里您为结构struct S2 { int foo; int bar; int stud_roll[]; } *s2g; /* note the declaration as a pointer */ void test (void) { s2g = malloc (sizeof *s2g + ELEMENTS * sizeof *s2g->stud_roll); if (!s2g) { perror ("malloc-s2g"); exit (EXIT_FAILURE); } ... 以及sizeof *s2g的元素分配了存储空间,例如stud_roll。这样可以提供单次分配/单次分配。

一个简短的例子是:

ELEMENTS * sizeof *s2g->stud_roll

注意:,因为灵活数组成员为#include <stdio.h> #include <stdlib.h> #define ELEMENTS 10 struct S2 { int foo; int bar; int stud_roll[]; } *s2g; void test (void) { s2g = malloc (sizeof *s2g + ELEMENTS * sizeof *s2g->stud_roll); if (!s2g) { perror ("malloc-s2g"); exit (EXIT_FAILURE); } s2g->foo = 1; s2g->bar = 2; for (int i = 0; i < ELEMENTS; i++) s2g->stud_roll[i] = i + 1; } int main (void) { test(); printf ("s2g->foo: %d\ns2g->bar: %d\n", s2g->foo, s2g->bar); for (int i = 0; i < ELEMENTS; i++) printf (" %d", s2g->stud_roll[i]); putchar ('\n'); free (s2g); return 0; } ,所以不能有包含灵活数组成员的 struct数组-但您可以拥有指针数组,每个指针都有单独的分配)

使用/输出示例

static

答案 1 :(得分:1)

您需要为(struct S2).stud_roll分配内存。没有任何内存,您将超出范围。 Assimung没有填充sizeof(struct S2) == sizeof(int) + sizeof(int)-没有为stud_roll分配的内存,因为该成员“自己”不占用内存。

s2g.stud_roll = {0};

您不能在C语言中以这种方式分配数组。

您可以使用复合文字在堆栈上分配一些内存:

#define STUD_ROLL_SIZE  4

struct S2 * const s2g = (void*)((char[sizeof(struct S2) + STUD_ROLL_SIZE * sizeof(int)]){ 0 });

void test(void) {
    s2g->stud_roll[0] = 1;
    // or
    memcpy(s2g->stud_roll, (int[]){ 1, 2, 3, 4 }, 4 * sizeof(int));
}

或使用malloc动态分配内存,您需要分配比sizeof(struct S2)多的内存:

struct S2 *s2g = NULL;

void test(void) {
    s2g = malloc(sizeof(struct S2) + STUD_ROLL_SIZE * sizeof(int));
    if (s2g == NULL) {
        fprintf(stderr, "Abort ship! Abort ship!\n");
        exit(-1);
    }
    s2g->stud_roll[0] = 1;
    free(s2g);
}