在运行中创建结构实例?

标签 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);
}

当执行这段代码时,它做了它应该做的,但它给了我一个段错误通知。我该怎么办?

最佳答案

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

可以使用“自动存储”:

// 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);
}

但是,您应该记住将返回类型放在您的函数中……将它们排除在外让人想起 1980 年代的 C……

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

void print(struct test *instance, int id)

关于在运行中创建结构实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27472830/

相关文章:

c - 在字符串数组的 malloc 上出现段错误。请帮忙

c - 这个汇编语句是什么意思?

c++ - 是否有必要在关闭 QFile 之前刷新 QTextStream?

ubuntu - 从源代码构建 llvm 3.42 时 gcc 崩溃(使用 cmake)

c - 使用 pthreads 来加速从 0 到 N 计算质数的处理。我使用它们是否正确?

c - 错误 : storage class specified for parameter

linux - Sed 语句不工作 Linux Raspbian

.net - 如何挂载 AWS I3 实例存储设备并在 Docker 中从 C# 应用程序使用

c - 为什么添加多余的掩码和位移位更可优化?

c++11 - bad_alloc 与 unordered_mapinitializer_list 和 MMX 指令,可能的堆损坏?