home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: sparky!uunet!spool.mu.edu!sol.ctr.columbia.edu!ira.uka.de!math.fu-berlin.de!informatik.tu-muenchen.de!LRZnews!regent!pal
- From: pal@regent.e-technik.tu-muenchen.dbp.de (Peter Loibl)
- Subject: Re: Macros
- Message-ID: <pal.721305765@regent.e-technik.tu-muenchen.de>
- Sender: news@regent.e-technik.tu-muenchen.de (News System)
- Organization: Technical University of Munich, Germany
- References: <1dfs04INNg3e@usenet.INS.CWRU.Edu>
- Date: Mon, 9 Nov 1992 10:42:45 GMT
- Lines: 65
-
- wct@po.CWRU.Edu (William C. Thompson) writes:
-
- >I'm trying to write a macro that allocates memory for Rows double *,
- >and then allocating for Cols double. Basically, A is a double **,
- >which points to a row of double *, which point to a buffer of doubles.
- >A[i][j] is then the jth element in the ith row. But I'm having
- >trouble with this macro business. I don't want to write a function
- >to do it.
-
- >ALL.H
- >-----
- >#define malloc2d(A,rows,cols); (
- >{
- > int i;
- >
- > if (((A)=(double **)malloc(sizeof(double *)*(rows)))==NULL)
- > printf("Allocation error!\n");
- > for (i=0; i<(cols); i++)
- > if (((A)[i]=(double *)malloc(sizeof(double)*(cols)))==NULL)
- > printf("Allocation error!\n");
- >}
- >)
-
- >TEST PROGRAM
- >------------
- >#include <stdio.h>
- >#include <all.h>
-
- >double **A;
- >int i,j;
-
- >main()
- >{
- > malloc2d(A,50,50);
- > for (i=0; i<50; i++)
- > for (j=0; j<50; j++)
- > A[i][j]=1.0/(i+j+1.0);
- > return 0;
- >}
-
- >It doesn't compile, though. What gives? E-mail responses, please...
-
- Hi!
-
- 1. It would be very usefull to know which compiler you are using. I
- know a few compilers, whose pre-processors don't expand long macros!
-
- 2. Your macros is wrong! Well as a function it should work, bit you have
- to tell the pre-processor, that your macro continues on the next
- line. It looks then like this:
-
- #define malloc2d(A,rows,cols); \
- { \
- int i; \
- if (((A)=(double **)malloc(sizeof(double *)*(rows)))==NULL) \
- printf("Allocation error!\n"); \
- for (i=0; i<(cols); i++) \
- if (((A)[i]=(double *)malloc(sizeof(double)*(cols)))==NULL) \
- printf("Allocation error!\n"); \
- }
-
- Tip: use fprintf(stderr, "Allocation error!\n") insead of printf(...).
-
- Peter Loibl
- pal@regent.e-technik.tu-muenchen.de
-