2011-10-18 81 views
-2
創建函數

是否可以從struct創建函數?從struct

像這樣:

#include <stdio.h> 

struct dma 
{ 
    int day, mes, year; 
}; 

dma *x(int a, int b, int c) 
{ 
} 

int main(int argc, char *argv[]) 
{ 
} 

和,這個函數返回一個結構..

如果可能的話,我該如何使用呢?

+0

你在尋找一個函數'屬於'結構[OOP概念中的方法]還是返回結構的函數?請解釋一下 – amit

+0

你想問什麼? –

回答

2

不知道你想完成什麼,但也許這是足夠接近?

struct dma 
{ 
    int day, mes, year; 
}; 

struct dma *x(int a, int b, int c) 
{ 
    struct dma *res = (struct dma *)malloc(sizeof(struct dma)); 
    res->day = a; 
    res->mes = b; 
    res->year = c; 
    return res; 
} 

int main(int argc, char *argv[]) 
{ 
    struct dma *m = x(1, 2, 3); 

    printf("Year: %d\n", m->year); 

    free(m); 
    return 0; 
} 
+0

錯誤C2440:'初始化':無法從'void *'轉換爲'dma *':( – Alexandre

+0

糟糕。編輯過的源代碼。 請注意完全沒有錯誤檢查/處理,應在實際使用之前添加。 ) – Kaos