home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #26 / NN_1992_26.iso / spool / comp / lang / c / 16204 < prev    next >
Encoding:
Text File  |  1992-11-09  |  2.2 KB  |  77 lines

  1. Newsgroups: comp.lang.c
  2. Path: sparky!uunet!spool.mu.edu!sol.ctr.columbia.edu!ira.uka.de!math.fu-berlin.de!informatik.tu-muenchen.de!LRZnews!regent!pal
  3. From: pal@regent.e-technik.tu-muenchen.dbp.de (Peter Loibl)
  4. Subject: Re: Macros
  5. Message-ID: <pal.721305765@regent.e-technik.tu-muenchen.de>
  6. Sender: news@regent.e-technik.tu-muenchen.de (News System)
  7. Organization: Technical University of Munich, Germany
  8. References: <1dfs04INNg3e@usenet.INS.CWRU.Edu>
  9. Date: Mon, 9 Nov 1992 10:42:45 GMT
  10. Lines: 65
  11.  
  12. wct@po.CWRU.Edu (William C. Thompson) writes:
  13.  
  14. >I'm trying to write a macro that allocates memory for Rows double *,
  15. >and then allocating for Cols double.  Basically, A is a double **,
  16. >which points to a row of double *, which point to a buffer of doubles.
  17. >A[i][j] is then the jth element in the ith row.  But I'm having
  18. >trouble with this macro business.  I don't want to write a function
  19. >to do it.
  20.  
  21. >ALL.H
  22. >-----
  23. >#define malloc2d(A,rows,cols); (
  24. >{
  25. >  int i;
  26. >
  27. >  if (((A)=(double **)malloc(sizeof(double *)*(rows)))==NULL)
  28. >    printf("Allocation error!\n");
  29. >  for (i=0; i<(cols); i++)
  30. >    if (((A)[i]=(double *)malloc(sizeof(double)*(cols)))==NULL)
  31. >     printf("Allocation error!\n");
  32. >}
  33. >)
  34.  
  35. >TEST PROGRAM
  36. >------------
  37. >#include <stdio.h>
  38. >#include <all.h>
  39.  
  40. >double **A;
  41. >int i,j;
  42.  
  43. >main()
  44. >{
  45. >  malloc2d(A,50,50);
  46. >  for (i=0; i<50; i++)
  47. >    for (j=0; j<50; j++)
  48. >      A[i][j]=1.0/(i+j+1.0);
  49. >  return 0;
  50. >}
  51.  
  52. >It doesn't compile, though.  What gives?  E-mail responses, please...
  53.  
  54. Hi!
  55.  
  56. 1. It would be very usefull to know which compiler you are using. I
  57.    know a few compilers, whose pre-processors don't expand long macros!
  58.  
  59. 2. Your macros is wrong! Well as a function it should work, bit you have
  60.    to tell the pre-processor, that your macro continues on the next
  61.    line. It looks then like this:
  62.  
  63. #define malloc2d(A,rows,cols); \
  64. { \
  65.   int i; \
  66.   if (((A)=(double **)malloc(sizeof(double *)*(rows)))==NULL) \
  67.     printf("Allocation error!\n"); \
  68.   for (i=0; i<(cols); i++) \
  69.     if (((A)[i]=(double *)malloc(sizeof(double)*(cols)))==NULL) \
  70.      printf("Allocation error!\n"); \
  71. }
  72.  
  73. Tip: use fprintf(stderr, "Allocation error!\n") insead of printf(...).
  74.  
  75. Peter Loibl
  76. pal@regent.e-technik.tu-muenchen.de
  77.