c - 使用结构体指针访问结构体的指针成员

标签 c pointers data-structures

我在结构体内部定义了整数指针。并且我想使用结构体指针来使用该成员指针。我的代码如下所示:

#include<stdio.h>
#include<stdlib.h>

struct abc
{
        int *x;
};

int main()
{

        struct abc *p = (struct abc*)malloc(sizeof(struct abc));
        p->x = (int*)malloc(sizeof(int));
        p->x = 10;
        printf("The value is %d\n",p->x);
        free(p);
}

现在我得到的输出符合我的预期。但是我在编译时收到警告消息。警告消息是:

temp.c:14:7: warning: assignment makes pointer from integer without a cast [enabled by default]
temp.c:15:2: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat]

我也尝试过,

*p->x = 10
 printf("The value is %d\n",*p->x);

但它不起作用。

如何解决这个警告?

最佳答案

为了将值分配给指针指向的内存地址,在用作左值时必须取消引用指针。例如:

*p->x = 10;

分配内存时,无需强制转换malloc的返回值。 malloc(和 calloc 等...)仅返回一个没有类型(或者是类型 void< 的内存地址)/)。此外,当您使用 'sizeof object' 时,您消除了指定类型时出错的风险(当 typedef 的被使用等)。例如,您的分配应该是:

struct abc *p = malloc (sizeof *p);
p->x = malloc (sizeof *p->x);

最后,在您编写的动态分配内存的任何代码中,对于分配的任何内存块,您都有两个责任:(1)始终保留指向内存块起始地址的指针,(2)它可以是当不再需要时被释放。

您必须使用内存错误检查程序来确保您没有在分配的内存块之外进行写入,尝试读取或基于未初始化的值进行跳转,最后确认您已释放所有内存您分配的内存。这是你做不到的事情。如果您分配它,请在不再需要时释放它。例如:

free (p->x);
free (p);

有许多微妙的方法可以滥用新的内存块。使用内存错误检查器可以让您识别任何问题并验证您分配的内存的正确使用,而不是通过段错误找出存在的问题。对于 Linux,valgrind 是内存错误检查器的正常选择。每个平台都有类似的内存检查器。它们使用起来都很简单,只需通过它运行您的程序即可。例如:

$ valgrind ./bin/struct_simple
==21079== Memcheck, a memory error detector
==21079== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==21079== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==21079== Command: ./bin/struct_simple
==21079==

 The value is 10

==21079==
==21079== HEAP SUMMARY:
==21079==     in use at exit: 0 bytes in 0 blocks
==21079==   total heap usage: 2 allocs, 2 frees, 12 bytes allocated
==21079==
==21079== All heap blocks were freed -- no leaks are possible
==21079==
==21079== For counts of detected and suppressed errors, rerun with: -v
==21079== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)

您想要确认所有堆 block 均已释放 - 不可能发生泄漏错误摘要:0 个上下文中出现 0 个错误

祝您在新的一年里编码顺利。

关于c - 使用结构体指针访问结构体的指针成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34554026/

相关文章:

C - 使用 getchar() 读取意外字符

c - 如何将数组的元素依次插入到另一个数组中?

c# - 为什么 C# 中的 Stack<T> 类允许 ElementAt(index) 而它是一个 ADT?

java - 具有 "object expiration"的对象缓存数据结构

c - 部分链接到 C 中的动态链接

c - strncpy 和 strxfrm 之间的区别

c - 无法找到-lGL,没有符号链接(symbolic link)怎么办?

c++ - 常量之间的区别。指针和引用?

c - 尝试进行内存分配时出现访问冲突错误

algorithm - 为什么 big-Oh 并不总是算法的最坏情况分析?