CentForever

C++堆栈生长方向

栈区:临时区

#include <iostream>

using namespace std;
#include <stdio.h>
int main()
{
    int a=100;
    int b=10;
    cout<<"/********************************/"<<endl;
    printf("%d\n",&a);
    printf("%d\n",&b);
    if(&a>&b){
        cout<<"down"<<endl;
    }else{
         cout<<"up"<<endl;
    }
    int c[10];
    cout<<"/********************************/"<<endl;
    for(int i=0;i<10;i++){
        c[i]=i;
    }
    cout<<"/********************************/"<<endl;
    for(int j=0;j<10;j++){
        printf("%d\n",&c[j]);
    }
    cout<<"/********************************/"<<endl;
    float *p=NULL;
    double *q=NULL;
    printf("%d\n",p);
    printf("%d\n",q);
     printf("%d\n",&p);
    printf("%d\n",&q);

    cout<<"/********************************/"<<endl;
    return 0;
}

  结论:&a>&b.先定义的变量a,后定义的变量b。变量a变量b都在临时区。因此栈向下生长的。对于数组地址随着下标越来越大,这是由于栈的生长方向和内存空间buf存放方向是两个不同的概念。

堆区:

#include <iostream>

using namespace std;
#include <stdio.h>
#include <stdlib.h>
int main()
{

    char *p=NULL;
    char *q=NULL;
    p=(char *)malloc(16*sizeof(char));
    q=(char *)malloc(16*sizeof(char));
    printf("\n%d\n",sizeof(char));
    printf("%d\n",&p);
    printf("%d\n",&q);
    printf("\np[0]:%d", &p[0]);
    printf("\np[1]:%d", &p[1]);
     printf("\nq[0]:%d", &q[0]);
    printf("\nq[1]:%d", &q[1]);
    if(p!=NULL){
        free(p);
    }
    if(q!=NULL){
        free(q);
    }

    return 0;
}

  结论:先定义的p指针和malloc区,在定义q指针和malloc区。在堆区p[0]比q[0]的大。而且p[1]比p[0]大。可知,堆是向上生长的。

posted on 2015-07-15 21:47  CentForever  阅读(1082)  评论(0编辑  收藏  举报

导航