home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #31 / NN_1992_31.iso / spool / comp / lang / c / 19108 < prev    next >
Encoding:
Text File  |  1992-12-31  |  2.1 KB  |  68 lines

  1. Newsgroups: comp.lang.c
  2. Path: sparky!uunet!psinntp!sunic!kth.se!news.kth.se!d90-awe
  3. From: d90-awe@klara.nada.kth.se (Assar Westerlund)
  4. Subject: Re: allocs, multidim arrays, and FAQ
  5. In-Reply-To: almeida@ame.gsfc.nasa.gov's message of Thu, 31 Dec 1992 17:03:07 GMT
  6. Message-ID: <D90-AWE.93Jan1045636@klara.nada.kth.se>
  7. Sender: usenet@kth.se (Usenet)
  8. Nntp-Posting-Host: klara.nada.kth.se
  9. Organization: Royal Institute of Technology, Stockholm, Sweden
  10. References: <1992Dec31.170307.4524@nsisrv.gsfc.nasa.gov>
  11. Date: Fri, 1 Jan 1993 03:56:36 GMT
  12. Lines: 54
  13.  
  14. In article <1992Dec31.170307.4524@nsisrv.gsfc.nasa.gov> almeida@ame.gsfc.nasa.gov (aswin m. almeida) writes:
  15.    Recently I attempted to create a small fragment of C
  16.    using the FAQ in the newsgroup.  Here is the fragment
  17.    from:
  18.  
  19.    [ cites the FAQ ]
  20.  
  21.    2) The Program I wrote (I am new to C programming, don't laugh <: )
  22.       (Implements the code above).
  23.  
  24. I've modified your program a little. Here is the modified version:
  25.  
  26. #include <stdio.h>
  27. #include <stdlib.h> 
  28.  
  29. int main(void)
  30. {
  31.      int i,j;
  32.      int nrows, ncolumns;
  33.      int **array;
  34.      ncolumns = 10;
  35.  
  36.      printf ("Enter array index: \n");
  37.      scanf ("%d", &nrows);
  38.  
  39.      array = (int **) malloc (nrows * sizeof(int *));
  40.      for (i=0; i < nrows; i++)
  41.       array[i] = (int *) malloc (ncolumns * sizeof(int));
  42.  
  43.      printf ("Reading array values, and printing\n");
  44.      for (i=0; i<nrows; i++)
  45.       for (j=0; j<ncolumns; j++)
  46.       {
  47.            printf("%d x %d = %d\n",i,j,i*j);
  48.            array[i][j] = i*j;
  49.            printf("%d,%d = %d\n",i,j,array[i][j]);
  50.            
  51.       }
  52.      return EXIT_SUCCESS;
  53. }
  54.  
  55. Notes:
  56.  
  57. 1. You should include stdlib.h, malloc is declared there.
  58. 2. Better declare main as int main(void) or if you have an "old-style"
  59. compiler int main().
  60. 3. Also return a value from main, EXIT_SUCCESS or if don't have an
  61. ANSI-compiler, 0.
  62. 4. The main problem you were having is that all declarations must come
  63. immediately after the open brace. I've moved the declaration of array
  64. up.
  65. 5. The size in the second malloc should be `ncolumns * sizeof(int)'.
  66. 6. You had put the for-loops in the wrong order (or the indexes in the
  67. wrong order).
  68.