当我有一个指向结构的指针时,为什么我必须使用 malloc? [英] Why do I have to use malloc when I have a pointer to a struct?

查看:36
本文介绍了当我有一个指向结构的指针时,为什么我必须使用 malloc?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 struct element {
     int val;
     int z;
 };
 typedef struct element ELEM;

看看这个例子:

 int main()
 {

    ELEM z;
    z =  6;
    printf("%d",z);
 }

一切正常,但如果我有一个指向结构的指针,我需要编写这样的代码:

Everything work fine , but if I have a pointer to structure I need to write the code like this:

ELEM *z;
p = (ELEM*)malloc(sizeof(ELEM)); // Without this will not work
(*p).val = 3;
p = (ELEM*)malloc(sizeof(ELEM));
printf("%d",(*p).val);

推荐答案

声明一个指针只会创建一个指针.必须有一些东西可以指向 这就是 malloc 给你的.

Declaring a pointer doesn't create anything but a pointer. Gotta have something for it to point to, which is what malloc gives you.

或者,您可以在堆栈上创建结构(又名自动存储"):

Alternatively, you could have created the struct on the stack (a.k.a. "automatic storage"):

ELEM z;
ELEM *p = &z;
(*p).val = 3; // Also could be written as p->val = 3;
printf("%d",(*p).val);

顺便说一句,你的指针代码有一个错误,因为它泄漏(即丢失了)第一个分配的结构:

BTW, your pointer code has an error, in that it leaks (i.e. loses track of) the first allocated struct:

ELEM *p;
p = (ELEM*)malloc(sizeof(ELEM));
(*p).val = 3;
p = (ELEM*)malloc(sizeof(ELEM)); // <- leak here: pointer to old struct lost.
printf("%d",(*p).val);

删除第二个 malloc 可以解决问题.一个完整的、修复过的版本,看起来更像您在使用中看到的代码:

Deleting the second malloc fixes the problem. A full, fixed-up version that looks more like code you'd see in use:

ELEM *p = (ELEM*)malloc(sizeof(ELEM));
p->val = 3;
printf("%d\n", p->val);
free(p);

每个 malloc 都应该有一个 free,除非你的程序通过终止来释放它的内存.即便如此,拥有 free 也很好.

Every malloc should have a free, unless your program releases it memory by terminating. And even then, it's nice to have the free.

这篇关于当我有一个指向结构的指针时,为什么我必须使用 malloc?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆