跳转至

Week4

Memory Model

int i;         // global vars
static int j;  // static global vars

void f()
{
    int k;          // local vars
    static int l;   // static local vars
    int *p = malloc(sizeof(int)); // allocated vars
}

以上是5种变量定义;

int globalx = 100;

int main()
{
    static int staticx = 30;
    int localx = 3;
    int *px = (int*) malloc(sizeof(int));

    cout << "&globalx = " << &globalx << endl;
    cout << "&staticx = " << &staticx << endl;
    cout << "&localx = " << &localx << endl;
    cout << "&px = " << &px << endl;
    cout << "px = " << px << endl;

}

Passing Address

#include <iostream>
using namespace std;

struct Student
{
    int id;
};

void foo(const Student *ps) // 指针传入的写法
{
    cout << ps->id << endl;
    cout << (*ps).id << endl;
}

void bar(const Student &s) // 传引用避免拷贝
{
    cout << s.id << endl;
}

int main()
{
    const Student s = {1001};
    foo(&s);
    bar(s);
}