home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: sparky!uunet!psinntp!sunic!kth.se!news.kth.se!d90-awe
- From: d90-awe@klara.nada.kth.se (Assar Westerlund)
- Subject: Re: allocs, multidim arrays, and FAQ
- In-Reply-To: almeida@ame.gsfc.nasa.gov's message of Thu, 31 Dec 1992 17:03:07 GMT
- Message-ID: <D90-AWE.93Jan1045636@klara.nada.kth.se>
- Sender: usenet@kth.se (Usenet)
- Nntp-Posting-Host: klara.nada.kth.se
- Organization: Royal Institute of Technology, Stockholm, Sweden
- References: <1992Dec31.170307.4524@nsisrv.gsfc.nasa.gov>
- Date: Fri, 1 Jan 1993 03:56:36 GMT
- Lines: 54
-
- In article <1992Dec31.170307.4524@nsisrv.gsfc.nasa.gov> almeida@ame.gsfc.nasa.gov (aswin m. almeida) writes:
- Recently I attempted to create a small fragment of C
- using the FAQ in the newsgroup. Here is the fragment
- from:
-
- [ cites the FAQ ]
-
- 2) The Program I wrote (I am new to C programming, don't laugh <: )
- (Implements the code above).
-
- I've modified your program a little. Here is the modified version:
-
- #include <stdio.h>
- #include <stdlib.h>
-
- int main(void)
- {
- int i,j;
- int nrows, ncolumns;
- int **array;
- ncolumns = 10;
-
- printf ("Enter array index: \n");
- scanf ("%d", &nrows);
-
- array = (int **) malloc (nrows * sizeof(int *));
- for (i=0; i < nrows; i++)
- array[i] = (int *) malloc (ncolumns * sizeof(int));
-
- printf ("Reading array values, and printing\n");
- for (i=0; i<nrows; i++)
- for (j=0; j<ncolumns; j++)
- {
- printf("%d x %d = %d\n",i,j,i*j);
- array[i][j] = i*j;
- printf("%d,%d = %d\n",i,j,array[i][j]);
-
- }
- return EXIT_SUCCESS;
- }
-
- Notes:
-
- 1. You should include stdlib.h, malloc is declared there.
- 2. Better declare main as int main(void) or if you have an "old-style"
- compiler int main().
- 3. Also return a value from main, EXIT_SUCCESS or if don't have an
- ANSI-compiler, 0.
- 4. The main problem you were having is that all declarations must come
- immediately after the open brace. I've moved the declaration of array
- up.
- 5. The size in the second malloc should be `ncolumns * sizeof(int)'.
- 6. You had put the for-loops in the wrong order (or the indexes in the
- wrong order).
-