GTK Gossip: 記憶體配置
来源:互联网 发布:乐器演奏软件 编辑:程序博客网 时间:2024/06/14 04:25
GLib提供了對C標準 malloc()、calloc、realloc()、free() 等函式的可攜版本記憶體相關處理函式,例如g_malloc()、g_malloc0()、g_realloc()、g_free()等函式,例如g_malloc()定義如下:
gpointer g_malloc (gsize n_bytes);
g_malloc0()則是會在配置記憶體之後,將所有的值設定為0,以下舉個簡單的動態陣列配置的例子:
- g_malloc_demo.c
#include <glib.h>
int main(int argc, char *argv[]) {
int size = 0;
printf("請輸入陣列長度:");
scanf("%d", &size);
int *arr = g_malloc0(size * sizeof(int));
int i;
printf("顯示元素值:/n");
for(i = 0; i < size; i++) {
printf("arr[%d] = %d/n", i, *(arr+i));
}
printf("指定元素值:/n");
for(i = 0; i < size; i++) {
printf("arr[%d] = ", i);
scanf("%d" , arr + i);
}
printf("顯示元素值:/n");
for(i = 0; i < size; i++) {
printf("arr[%d] = %d/n", i, *(arr+i));
}
g_free(arr);
return 0;
}
一個執行結果如下所示:
顯示元素值:
arr[0] = 0
arr[1] = 0
arr[2] = 0
指定元素值:
arr[0] = 1
arr[1] = 2
arr[2] = 3
顯示元素值:
arr[0] = 1
arr[1] = 2
arr[2] = 3
g_malloc()配置失敗,則應用程式會中止,您可以使用g_try_malloc(),在配置失敗後會傳回NULL值。
如果要建立struct配置,則可以使用g_new(),使用g_new0()則會將所有strut初始為0,例如:
#include <glib.h>
struct _Ball {
char color[10];
double radius;
};
typedef struct _Ball Ball;
int main(int argc, char*argv[]) {
Ball *ball = g_new(Ball, 3);
....
return 0;
}
struct _Ball {
char color[10];
double radius;
};
typedef struct _Ball Ball;
int main(int argc, char*argv[]) {
Ball *ball = g_new(Ball, 3);
....
return 0;
}
傳回的指標已經是相對應的型態,無需再進行CAST。
您可以看看Memory Allocation 了解更多有關 GLib 的記憶體配置函式。
- GTK Gossip: 記憶體配置
- GTK Gossip: Ubuntu 下安裝 GTK
- GTK Gossip: GTK 事件處理函式
- GTK Gossip: GtkTable
- GTK Gossip: 簡介 Glade
- GTK Gossip: GtkMessageDialog
- GTK Gossip: GtkAboutDialog
- GTK Gossip: GtkEntry
- GTK Gossip: GtkSpinButton
- GTK Gossip: GtkTextView
- GTK Gossip: GtkComboBox
- GTK Gossip: GtkNotebook
- GTK Gossip: GtkPaned
- GTK Gossip: GtkScrolledWindow
- GTK Gossip: GtkHandleBox
- GTK Gossip: GtkUIManager
- GTK Gossip: GtkProgressBar
- GTK Gossip: GtkToolBar
- MySQL 1130 错误
- 最简单的GDI+程序代码
- GTK Gossip: GTree 與 GNode
- PHP会话控制之session--实例
- perl正则内置变量匹配
- GTK Gossip: 記憶體配置
- asp中使用OpenSchema时出现“对象或提供程序不能执行所需操作”错误的原因
- GTK Gossip: GThread
- 随机生成一个多播地址
- 操作系统的内核态和用户态
- Vsftpd虚拟用户设置
- window server 2003 share folders
- 在xp安装IIS的时候找不到“Internet信息服务(IIS)”的解决办法。
- GTK Gossip: GMutex