在运行中创建结构实例?

时间:2014-12-14 18:54:14

标签: c linux gcc

我正在玩结构,并找到了一种方法来分配int类型的结构ID实例。

struct test{
 int x;
 int y;
}

assign(struct test *instance, int id, int x2, int y2)
{
 (instance+id)->x = x2;
 (instance+id)->y = y2;
}

print(struct test *instance, int id)
{
 printf("%d\n", (instance+id)->x);
}


main()
{
 struct test *zero;
 assign(zero, 1, 3, 3);
 print(zero, 1);
}

执行此代码时,它会执行应有的操作,但它会为我提供分段错误通知。我该怎么办?

1 个答案:

答案 0 :(得分:4)

您需要先为结构分配内存,然后才能使用它们。

您可以使用“自动存储”:

// You can't change COUNT while the program is running.
// COUNT should not be very large (depends on platform).
#define COUNT 10

int main()
{
    // Allocate memory.
    struct test zero[COUNT];

    assign(zero, 1, 3, 3);
    print(zero, 1);

    // Memory automatically freed.
}

或者您可以使用“动态存储”:

#include <stdlib.h>

int main()
{
    int count;
    struct test *zero;

    // You can change count dynamically.
    count = 10;

    // Allocate memory.
    // You can use realloc() if you need to make it larger later.
    zero = malloc(sizeof(*zero) * count);
    if (!zero)
        abort();

    assign(zero, 1, 3, 3);
    print(zero, 1);

    // You have to remember to free the memory manually.
    free(zero);
}

但是,你应该记得在你的功能上放置返回类型......让它们与20世纪80年代的C相似......

void assign(struct test *instance, int id, int x2, int y2)

void print(struct test *instance, int id)