c - 结构体内部指针的值

标签 c pointers struct

我写了这个简单的程序:

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

struct squ{
    int total;
};

struct rect{
    int width;
    int len;
    struct squ * p;
};

void init(struct rect *r){
    struct squ t;
    t.total = 100;
    
    r->width = 5;
    r->len = 5;
    r->p = &t;
}

void change(struct rect *r){
    struct squ *p = r->p;

    r->width = r->width * 10;
    r->len = r->len * 10;
    p->total = p->total * 10;
}

void main(){
    struct rect r1;
    init(&r1);
    struct squ *p = r1.p;

    printf("rec w: %d , l: %d, total: %d \n",r1.width, r1.len, p->total);
    change(&r1);
    printf("rec changed w: %d , l: %d, total: %d  \n",r1.width, r1.len, p->total);
}

但是程序的输出是这样的:

rec init w: 5 , l: 5, total: 25

rec changed w: 50 , l: 50, total: -1748423808

total 的值应该是 250,而不是这个数字。

最佳答案

问题是您没有分配t。相反,您使用的是本地堆栈值,一旦函数退出,该值将不存在。但是,您设置了指向该位置的指针,因此它将被最终使用该堆栈位置的任何其他内容填充。您需要分配内存。

我修改了你的程序以使用 malloc

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

struct squ{
    int total;
};

struct rect{
    int width;
    int len;
    struct squ * p;
};

void init(struct rect *r){
    struct squ *t;

    t = malloc( sizeof*t );
    if( NULL != t )
    {
        t->total = 100;

        r->width = 5;
        r->len = 5;
        r->p = t;
    }
    else
    {
        printf( "malloc fail\n" );
    }
}

void change(struct rect *r){
    struct squ *p = r->p;

    r->width = r->width * 10;
    r->len = r->len * 10;
    p->total = p->total * 10;
}

int main(){
    struct rect r1;
    init(&r1);
    struct squ *p = r1.p;

    printf("rec w: %d , l: %d, total: %d \n",r1.width, r1.len, p->total);
    change(&r1);
    printf("rec changed w: %d , l: %d, total: %d  \n",r1.width, r1.len, p->total);

    return 0;
}

这会产生输出:

rec w: 5 , l: 5, total: 100 
rec changed w: 50 , l: 50, total: 1000  
Program ended with exit code: 0

关于c - 结构体内部指针的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33071922/

相关文章:

c - C shell 内的多个管道

c++ - 从基类实例获取指向(纯)虚函数的指针

c++ - "no match for ' operator= '"in c++, 试图建立链表

c - 这个十六进制算术是如何工作的?

c - C 中结构体指针指向哪个地址?

swift - 什么时候我的结构太大了?

C# 枚举、结构和类

java - 将指针传递给指针以通过 JNA 从 Java float 到 C 动态库

c - c 中的位操作给出了意想不到的结果

c - 用于控制单独 GPIO 的 STM32 阵列