使用Microsoft Visual Studio 2010:C編程malloc宏問題
我可以在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;
}
感謝您的幫助。
返回類型通過malloc( )是void *,不要投它。 – blueshift 2012-03-30 07:08:51
謝謝您的評論,當然你是正確的。如果我嘗試在C++編譯器上編譯它,它會產生一個錯誤或警告。這是我在宏裏面演員的邏輯。是的,我應該在問題中指出這一點。爲此道歉。 – user1166780 2012-03-30 07:38:44