修复它的一种方法是这样:所以我发现的问题是,在你定义了支柱“点”之后,你声明了一个指向结构的指针“*ptt”,但你没有初始化它。所以ptt什么都没有;假设ptt指向垃圾。因此,在主函数的下方,您声明“*pqq”并初始化为 ptt 指向的地址。所以你声明“*pqq”并告诉它指向相同的地址ptt指向这个语句“pqq = ptt;”。但是不要忘记 ptt 最初并没有指向任何东西。所以现在你有 ptt 和 pqq 都指向垃圾。当你在这里调用函数时“pqq = pointer(100,123);” 该函数使用 ptt 直接访问其成员 x 和 y。但是 ptt 再次指向什么。所以该函数没有访问任何内容,因此没有返回任何内容到 pqq 中,pqq 也没有指向任何内容。所以程序崩溃是因为这是不允许的。你不能返回任何东西,因为你没有访问任何东西。所以我的解决方法是:当你声明指向结构的指针时,在使用它之前动态初始化它。有带有注释的固定代码:
#include <stdio.h> // header that defines the standard input and output routines
#include <stdlib.h> // header to use malloc()
//struct definition
struct point
{
int x;
int y;
}*ptt = NULL; // it's safe to first initialize pointers to NULL
//function definition
struct point *pointer(int c, int d)
{
ptt->x = c;
ptt->y = d;
return ptt;
}
int main()
{//main
ptt = (struct point*) malloc(sizeof( struct point)); //malloc() creates a space big enough to hold a variable of type "struct point" this way " malloc(sizeof( struct point))".
// But malloc() returns a pointer to void (void*) as return value
// so i type cast that value returned by malloc() into a pointer-to-struct this way "(struct point*)"
struct point *pqq = NULL; // it's safe to first initialize pointers to NULL
pqq = ptt; // now ptt points to the memory location given by the malloc function and pqq points to the same place as well
pqq = pointer(100, 123);
printf("Pointer value is %d\n", pqq->x);
free(ptt); // don't forget to free memory. You only need to free one pointer. Whichever one of them.
// Because both ptt and pqq point to the same memory location so by freeing one, you automatically free the other;
// Don't attempt to free both at the same time because that would generate a run time error since the C language standard does not allow to free the same memory location twice.
return 0;
}//end main
//Sorry for the long comment but i wanted to explain it in detail. Hope it helps.