Thread: newbie array help

  1. #1
    Registered User
    Join Date
    Oct 2004
    Posts
    3

    newbie array help

    Bah learning c here and I have trouble using arrays. very tricky for me.
    How is this code can I get an array to make a table of rows and columns being the same number as inputted by the user:
    Code:
    #include <stdio.h>
    
    int main(void)
    {
    	int input;
    	int x,y;
    	
    	
    	scanf("%d", &input);
    					
    	x=y=input;
    	int table[x][y];
    	
    	return 0;	
    }
    Thanks guys in advance

  2. #2
    Registered User
    Join Date
    Aug 2004
    Posts
    66
    to ask for the elements of an array you should always use a for()
    like, for example, you want an user to give the number of rows and columns, so you should do something like this:
    Code:
    printf("number of rows");
    scanf("%d", &row);
    printf("number of columns");
    scanf("%d", &col);
    
    for(a=0;a<row;a++){
      for(b=0;b<col;b++)
    	scanf("%d", table[a][b]);   //remember, [row][column], always is that way
    	}
    remember, you must always inizialize the variable as an array, giving a number of locations it should keep, example: arr[100][100]

  3. #3
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    You need to use malloc() for that and then there's really no simple way to do it as a 2D array. You could try something like this:
    Code:
    itsme@itsme:~/C$ cat dynarray.c
    #include <stdio.h>
    #include <stdlib.h>
    
    #define TABLE(y, x) (*((table) + (x) + (y) * (size)))
    
    int main(void)
    {
      char buf[10];
      int *table;
      int size;
    
      do
      {
        printf("Array size (1-9999)? ");
        fflush(stdout);
        fgets(buf, sizeof(buf), stdin);
        size = atoi(buf);
      } while(size < 1 || size > 9999);
    
      if(!(table = malloc(sizeof(int) * size * size)))
      {
        puts("Memory allocation error!");
        exit(EXIT_FAILURE);
      }
    
      TABLE(0, 0) = 3;
      printf("table[0][0] = %d\n", TABLE(0, 0));
    
      free(table);
      return EXIT_SUCCESS;
    }
    itsme@itsme:~/C$ ./dynarray
    Array size (1-9999)? 10
    table[0][0] = 3
    itsme@itsme:~/C$
    Last edited by itsme86; 10-24-2004 at 10:42 AM.
    If you understand what you're doing, you're not learning anything.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. 1-D array
    By jack999 in forum C++ Programming
    Replies: 24
    Last Post: 05-12-2006, 07:01 PM
  2. 2d array question
    By gmanUK in forum C Programming
    Replies: 2
    Last Post: 04-21-2006, 12:20 PM
  3. multidimensional array - newbie help
    By trixxma in forum C Programming
    Replies: 6
    Last Post: 03-25-2006, 06:32 PM
  4. question about multidimensional arrays
    By richdb in forum C Programming
    Replies: 22
    Last Post: 02-26-2006, 09:51 AM
  5. Replies: 5
    Last Post: 05-30-2003, 12:46 AM