簡體   English   中英

C編程malloc宏問題

[英]C Programming malloc macro issue

使用Microsoft Visual Studio 2010:

我可以在C語言中編寫此類宏嗎? 我無法自己工作。

#define MEM_ALLOC_C(type, nElements) (type = (type*)_aligned_malloc(nElements * sizeof(type), CACHE_ALIGNMENT))

如果我這樣寫,它將起作用:

#define MEM_ALLOC(type, nElements) (testFloat = (float*)_aligned_malloc(nElements * sizeof(float), CACHE_ALIGNMENT))

這就是我的使用方式:

#define CACHE_ALIGNMENT 16
#define INDEX 7
#define MEM_ALLOC(type, nElements) (type = (float*)_aligned_malloc(nElements * sizeof(float), CACHE_ALIGNMENT))
#define MEM_ALLOC_C(type, nElements) (type = (type*)_aligned_malloc(nElements * sizeof(type), CACHE_ALIGNMENT))
#define MEM_DEALLOC_PTR(type) (_aligned_free(type))

int _tmain(int argc, _TCHAR* argv[])
{
    float* testFloat;

    //MEM_ALLOC_C(testFloat, INDEX);    // Problem here.

    MEM_ALLOC(testFloat, INDEX);        // works

    //testFloat = (float*)_aligned_malloc(INDEX * sizeof(float), CACHE_ALIGNMENT);  // works

    testFloat[0] = (float)12;

    //MEM_DEALLOC_PTR(testFloat);       // If we call de-alloc before printing, the value is not 12.
                                    // De-alloc seems to work?

    printf("Value at [%d] = %f \n", 0, testFloat[0]);

    getchar();

    MEM_DEALLOC_PTR(testFloat);

return 0;
}

謝謝你的幫助。

考慮一下替換:

type = (type*)_aligned_malloc(nElements * sizeof(type), CACHE_ALIGNMENT)

變成

testFloat = (testFloat*)_aligned_malloc(INDEX * sizeof(testFloat), CACHE_ALIGNMENT)

沒有諸如testFloat*這樣的東西。

在純C語言中,無需強制轉換malloc的結果。 因此,您可以執行以下操作:

 #define MEM_ALLOC_C(var, nElements) (var = _aligned_malloc(nElements * sizeof(*var), CACHE_ALIGNMENT)) 

MEM_ALLOC_C()宏中的問題是您MEM_ALLOC_C()type參數用作類型和左值。 那行不通:

#define MEM_ALLOC_C(type, nElements) (type = (type*)_aligned_malloc(nElements * sizeof(type), CACHE_ALIGNMENT))
//                                    ^^^^    ^^^^                                     ^^^^
//                                   lvalue   type                                     type

請注意,在工作版本中,必須如何在左值處使用變量名,並在其他位置使用類型。

如果您確實想擁有這樣的宏,為什么不將其像函數一樣使用並將結果分配給指針,而不是將分配隱藏在宏內:

#define MEM_ALLOC_C(type, nElements) ((type*)_aligned_malloc(nElements * sizeof(type), CACHE_ALIGNMENT))

testFloat = MEM_ALLOC_C(float, INDEX);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM