<< 動畫結束 >>
簡單範例:
struct Package{
char msg[2];
};
char *get_string(char c){
char *result = malloc(sizeof(char)*2);
result[0] = c;
result[1] = '\0';
return result;
}
int main() {
char *s1 = get_string('A');
struct Package p;
strcpy(p.msg, s1);
free(s1);
return 0;
}
原則上就是一個 alloc(malloc, calloc, realloc) 配一個 free 來還記憶體上面程式可以來這裡(其實就是上面那個)看看記憶體怎麼跑喔OuO
參考資料:
Does a string created with 'strcpy' need to be freed?
malloc()、free()、calloc() 與 realloc()
沒有留言:
張貼留言