2009-10-26 41 views
4

如何以符合(ISO C99)的方式执行下列操作?ISO C相当于表达式中的支撑组

#define MALLOC(type, length, message) ({          \ 
     type * a_##__LINE__ = (type *)malloc((length) * sizeof(type));  \ 
     assert(message && (a_##__LINE__ != NULL));       \ 
     a_##__LINE__;              \ 
     }) 

double **matrix = MALLOC(double *, height, "Failed to reserve"); 

注:编译使用:GCC -std = C99 -pedantic ...

回答

4

你不应该把测试malloc()assert():它不会在当你被编译做一个发布版本。我没有在以下程序中使用assert()

#include <stdio.h> 
#include <stdlib.h> 

void *mymalloc(size_t siz, size_t length, 
       const char *message, const char *f, int l) { 
    void *x = malloc(siz * length); 
    if (x == NULL) { 
    fprintf(stderr, "a.out: %s:%d: MALLOC: " 
        "Assertion `\"%s\" && x != ((void *)0)' failed.\n", 
      f, l, message); 
    fprintf(stderr, "Aborted\n"); 
    exit(EXIT_FAILURE); 
    } 
    return x; 
} 

#define MALLOC(type, length, message)\ 
     mymalloc(sizeof (type), length, message, __FILE__, __LINE__); 

int main(void) { 
    int height = 100; 
    double **matrix = MALLOC(double *, height, "Failed to reserve"); 
    /* work; */ 
    free(matrix); 
    return 0; 
} 
+1

我会按照你的建议使用一个函数,并避免heisenbug(谢谢指出它)。 – Alexandru 2009-10-26 23:33:00

+0

+1为heisenbug :) – pmg 2009-10-26 23:36:21

4

没有与您正在使用的GCC扩展相同的标准。

使用函数(如果您使用C99,甚至可能是内联函数)代替宏中的代码,您可以实现等效结果。您仍然需要一个宏来调用该函数,因为其中一个参数是“类型名称”,您无法将它们传递给函数。

请参阅@pmg的答案,了解使用它的函数和宏的类型。