【发布时间】: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 标准可以。