c - 如何返回指向 C 结构体的指针...?

标签 c

我是 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/

相关文章:

c - 为什么*start=NULL必须在大括号外声明?我们不能写在里面吗?有什么意义吗

c - 文件输入/输出 : two file pointes

c - 如何使用 fscanf 有限制地读取 C 中的空格分隔文件?

c - ‘)’ token 和变量未声明错误之前的预期表达式

c - 微 Controller 中的多线程

c - 如何检查后台运算符(operator) '&' 的命令?

c - C 中的字符串动态分配

c - OpenCL 命令队列 (CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE) 不工作 (MacOS)

通过将 '0' 附加到较小长度的字符串来计算汉明距离

c - C中的简单for循环倒数计时器