指针在结构中的值

时间:2015-10-12 01:22:32

标签: 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,总数:25

     

rec改为w:50,l:50,总数:-1748423808

总值应为250,而不是此数字。

1 个答案:

答案 0 :(得分: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