我正在研究结构并找到了一种方法来分配 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/