[英]Value of pointer inside an struct
I wrote this simple program: 我写了这个简单的程序:
#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);
}
However the output of the program is this: 但是程序的输出是这样的:
rec init w: 5 , l: 5, total: 25
重新初始化w:5,l:5,总数:25
rec changed w: 50 , l: 50, total: -1748423808
记录已更改w:50,l:50,总数:-1748423808
The value of total should be 250, not this number. 总数的值应为250,而不是此数字。
Problem is that you are not allocating t
. 问题是您没有分配
t
。 Instead you are using a local stack value which will not exist once the function exits. 相反,您使用的是函数退出后将不存在的本地堆栈值。 However you set a pointer to that location, so it will get filled with whatever else happens to end up using that stack position.
但是,您将指针设置到该位置,因此它将使用该堆栈位置填充发生的任何其他情况。 You need to allocate the memory.
您需要分配内存。
I modified your program to use malloc 我修改了程序以使用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;
}
This produces the output: 产生输出:
rec w: 5 , l: 5, total: 100
rec changed w: 50 , l: 50, total: 1000
Program ended with exit code: 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.