2009年5月13日

C語言- 原來在function裡面回傳一個string只有兩種辦法

今天寫程式的時候發現一個問題: 要怎麼樣在C程式的function回傳一串文字? C程式回傳的東西只能是一個位址(char*), 程式像下面這樣寫的話

char* str_test(){
char a[20]="abcd";
return a;
}

會是嚴重的錯誤, 因為a是local var, 在離開str_test的時候就已經被free掉, 回傳的位址指向的東西將是一串無意義的東西。

所以只有兩種辦法可以做:

第一, 把a指向即使離開str_test也不會被free掉的地方, 就是heap區域, 注意: 但這需要用到heap區域的空間, 如果heap區域滿了, new指令也沒有用, 可能需要做new指令是否成功的檢查。

char* str_test(){

char* a= new char[20];
sprintf(a, "abcd");
return a;
}

第二, 直接把a指向的區域變成即使離開str_test也不會被release, 使用static指令, 但是這還是有點暴力。

char* str_test(){

static char a[20]= "abcd";
return a;
}

思考了一下, 最好的方式應該是把一個char*傳進去, 直接在function裡面更改指標指向的區域, function回傳void就好。

void str_test(char* result){
sprintf(result, "abcd");
//change result
}

雖然是很小的觀念, 但是影響很大, 指標的使用真的要很小心, 千萬不能讓指標指向的東西突然變成沒意義的東西。

ps. 雖說如此, c++的string卻可以做以下的事情:
#include

string str_test(){
string a="abcd";
return a;
}

改天要去找一下c++ STL的原始碼看看string是怎麼做的, 應該是多了不少個instruction作處理。

2009年5月6日

悶阿! 可是要加油!

日子一天天過去, 到底最後會是怎樣呢? 當然不可以認輸! 現在我要做的就是跟老師比速度, 她看的越慢我越要趕工弄起來給她看, 不想要以後再來後悔現在這段日子, 就是要跟她拼!它越要玩我我就越要趕東西出來給他看!

2009年5月3日

好聽的搖滾- Simple Plan "When I'm gone"


這是最近在sky.fm 的tophits channel 聽到的歌, 聽完一次主歌+副歌就覺得很棒, 趕快記下artist跟title。Simple Plan 樂團是法裔加拿大搖滾樂團, 已經發行過三張專輯, 最近的是2008年發行的"Simple Plan"同名專輯。

listen: Simple Plan- When I'm gone.
mv: When I'm gone
lyrics:
Simple Plan- When I'm Gone

We're doing it.

I look around me,
But all I seem to see,
Is people going no where,
Expecting sympathy.

It's like we're going through the motions,
Of a scripted destiny.
Tell me where's our inspiration,
If life wont wait,
I guess it's up to me.

[Chorus:]
Woah!
No, we're not gonna waste another moment in this town.
Woah!
And we won't come back your world is calling out.
Woah!
We'll leave the past in the past,
Gonna find the future.
If misery loves company well,
So long, you'll miss me when I'm gone.

Ooh, ooh, ooh.
You're gonna miss me when I'm gone.
Ooh, ooh, ooh.

Procrastination, running circles in my head.
While you sit there contemplating,
You wound up left for dead (left for dead)
Life is what happens while you're busy making your excuses.
Another day, another casualty.
And that won't happen to me.

[Chorus]

Ooh, ooh, ooh.
You're gonna miss me when I'm gone.
Ooh, ooh, ooh.
You're gonna miss me when I'm gone.
When I'm gone-

Let's go!

Won't look back,
When I say goodbye.
I'm gonna leave this a hole behind me,
Gonna take what's mine tonight.
Because every wasted day becomes a wasted chance.
You're gonna wake up feeling sorry,
Because life wont wait,
I guess it's up to you.

[Chorus]

Ooh, ooh, ooh.
You're gonna miss me when I'm gone.
Ooh, ooh, ooh.
You're gonna miss me when I'm gone.
Ooh, ooh, ooh.
You're gonna miss me when I'm gone.
Ooh, ooh, ooh.
You're gonna miss me when I'm gone.