简体   繁体   English

C struct变量分配?

[英]C struct variables allocation?

I'm new to C so please correct any mistakes I have. 我是C的新手所以请纠正我的错误。

Here's some code that's sort of like the code I have 这里的代码有点像我的代码

//typdef stuff for apple, *apple_t here
apple_t get() {
    apple a;
    a.num = 0;

    apple_t ap = &a;
    printf("set num to %d\n", ap->num);
    return ap;
}

// ap above is placed into read(ap)
void read(apple_t ap) {
    printf("num: %d\n", ap->num);
}

Why is it that for the "set" print ap->num == 0, but when I do the printf in read function I get some junk number like -1218550893? 为什么对于“set”打印ap-> num == 0,但是当我在read函数中执行printf时,我会得到一些像-1218550893这样的垃圾编号? What's going on? 这是怎么回事? Is the integer set being freed? 是否释放了整数集? What is C doing? C做什么? And how do you fix this? 你是如何解决这个问题的?

You are returning the address of a local variable. 您正在返回本地变量的地址。

In this case the variable a is a local variable. 在这种情况下,变量a是局部变量。 It is lost after the function ends. 功能结束后丢失。

There are two options to fix this: 有两种方法可以解决这个问题:

  1. Return it by value. 按价值归还。 Don't return its address. 不要归还其地址。
  2. Allocate memory for it using malloc() . 使用malloc()为它分配内存。 But you must be sure to free() it later. 但你必须确保以后free()它。

You are returning a local variable, that is not available after the function has returned. 您将返回一个局部变量,该函数在函数返回后不可用。

C supports returning structs, so no need for a pointers at all: C支持返回结构,因此根本不需要指针:

apple_t get() {
    apple_t a;
    a.num = 0;
    return a;
}

The following code will copy the result, not returning a local variable. 以下代码将复制结果,而不是返回局部变量。

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

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