我是 C 编程新手...... 这是我的示例代码......
我想编写一个应该返回指向结构的指针的函数...当我编译下面的代码时...我遇到了段错误... 我知道,我犯了一些小错误...对此问题的任何建议都会对我有帮助...
#include<stdio.h>
struct point *test(int x, int y);
struct point {
int x;
int y;
};
int main() {
struct point* val2;
int xx, yy;
xx = 1;
yy = 2;
val2 = test(xx, yy);
}
struct point *test (int xx, int yy) {
struct point *a;
a->x = xx;
a->y = yy;
return (a);
}
使用的Makefile
CC = gcc
Phony = .clean
main: main.o
$(CC) $< -o $@
main.o: main.c
$(CC) -c $<
clean:
rm *.o
收到的输出:
Segmentation fault(Core dumped)
最佳答案
谢谢大家的建议。
此代码解决了问题......
struct point *test (int xx, int yy) {
struct point *a = malloc(sizeof *a);
a->x = xx;
a->y = yy;
return (a);
}
关于c - 如何返回指向 C 结构体的指针...?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43351660/