简体   繁体   English

指向结构的指针

[英]Pointer to a struct

I'm trying to understand pointers more and am having trouble with this example. 我试图更多地了解指针,并且在此示例中遇到了麻烦。

 typedef struct{
    int areaCode;
    int streetNumber;
 }Address;
 Address *addr;
 addr->areaCode = 10000;
 printf("%d\n", addr->areaCode);

I get a segmentation fault and can't seem to understand why. 我遇到了细分错误,似乎无法理解原因。

addr is a pointer to a Address struct, so I also tried: addr是指向Address结构的指针,因此我也尝试过:

 *addr->areaCode = 10000;

and also got a "indirection requires pointer operand ", any ideas? 并且还得到了“间接要求指针操作数”,有什么想法吗?

Address *addr;

You only declared a pointer addr , but it points to somewhere unknown. 您只声明了一个指针addr ,但它指向未知的地方。 You didn't allocate memory space for it. 您没有为其分配内存空间。

To fix it, change into 要修复它,请更改为

Address *addr = malloc(sizeof(Address));

You haven't allocated memory for structure object. 您尚未为结构对象分配内存。 Either use malloc() or simply declare variable of type Address instead of pointer to Address (in which case to access member use . operator instead of -> ). 要么使用malloc()或简单地声明类型的可变Address ,而不是指针Address (在这种情况下,访问部件使用.操作者而不是-> )。

Option one: 选项一:

Address *addr = malloc(sizeof *addr); // don't forget #include <stdlib.h>
if (addr == NULL) {
    // handle failed allocation
}
// ...
free(addr); // free(addr), addr = NULL; if you like

Option two: 选项二:

Address addr;

addr is uninitialised and so contains some 'random' value. addr未初始化,因此包含一些“随机”值。 De-referencing an uninitialised pointer causes... problems. 取消引用未初始化的指针会导致...问题。
Accessing memory that you are not allowed to = segmentation fault. 无法访问的内存=分段错误。
Accessing random memory that doesn't seg-fault leads to memory corruption. 访问没有分段错误的随机内存会导致内存损坏。

You can do: 你可以做:

Address myAddress;
Address *addr = &myAddress;

and this will work. 这会起作用。 Allocate first then aquire pointer. 首先分配,然后获取指针。
This will produce a pointer to the Address on the stack. 这将产生一个指向堆栈上Address的指针。 Beware of it going out of scope at the end of the function. 当心在函数末尾超出范围。

You can also do: 您也可以这样做:

Address *addr = malloc(sizeof(Address));

This allocates on the heap so the actual Address won't go out of scope. 这在堆上分配,因此实际的Address不会超出范围。 But you do need to remember to free(addr); 但是您确实需要记住要free(addr); or you introduce a memory leak. 否则会导致内存泄漏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM