code.club

標題: new和delete的用法 [打印本頁]

作者: enter    時間: 2015-10-19 23:41
標題: new和delete的用法
本帖最後由 enter 於 2015-10-20 15:12 編輯

#include <iostream>

using namespace std;

int main(int argc, char *argv[]) {
       
        float *f; //表示這是一個float型的指標變數
        long *l;
        char *c,*d;
       
        f = new float; //為此指標變數劃出一塊同型的記憶體區塊
        l = new long;
        c = new char;
        d = new char;
       
        *f = 2.3; //給指標變數賦值,如同傳統做法一般
        *l = 1234;
        *c = 'G'; //這樣只能輸入字元
        strcpy(d,"hello world"); //要賦值字串則需要用strcpy()的方式
       
        cout<<*f<<endl<<*l<<endl<<*c<<endl<<d<<endl; //要印出字串則d不能用指標*符號
       
        //delete f; //看似刪掉這個指標變數,其實是釋放它所指向的記憶體,但似乎不是刪掉這指標變數本身
        //delete l;
        //delete c;
       
        *f = 99.99; //因為可以又賦值給它們而不用再定義,但其實不用刪前面也可以重新賦值?
        *l = 88888;
        *c = 'W';
        strcpy(d,"good idea");
       
        cout<<*f<<endl<<*l<<endl<<*c<<endl<<d<<endl;
               
        return 0;
       
}




歡迎光臨 code.club (http://code.club/) Powered by Discuz! X3.2