我写了这个简单的程序:
#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/