【问题标题】:Value of pointer inside an struct结构内指针的值
【发布时间】:2015-10-12 01:22:31
【问题描述】:

我写了这个简单的程序:

#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 改变 w: 50 , l: 50, total: -1748423808

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

【问题讨论】:

  • init() 导致指向具有自动存储持续时间的对象的指针在其生命周期结束后可见。
  • struct squ t; 在堆栈上,您不能在范围之外使用指针。你必须 malloc 它
  • @Ôrel:这就是我所说的
  • 你没有定义自动存储下界的生命周期
  • @Ôrel:我为什么要定义这些术语? C 标准可以。

标签: c pointers struct


【解决方案1】:

问题是您没有分配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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-04
    • 1970-01-01
    • 2012-04-22
    • 1970-01-01
    相关资源
    最近更新 更多