Dynamic 2d Array

This is a discussion on Dynamic 2d Array within the C Programming forums, part of the General Programming Boards category; This my attempt at creating a dynamic 2d array. I am able to store the values into the array and ...

  1. #1
    Registered User
    Join Date
    Dec 2008
    Posts
    15

    Dynamic 2d Array

    This my attempt at creating a dynamic 2d array. I am able to store the values into the array and read them out. Is there a more elegant way of inputing the values?

    Code:
    array[(i*4)+j]=count++;
    instead of having to multiplying i*4.


    Code:
    #include<stdio.h>
    
    int main(void){
    	
            int *array;
            int column,row;	
    	int i,j,count;
    
    	printf("Please Enter the dimensions of the array:\n");
    	
    	printf("row=");
    	scanf("%d",&row);
    	printf("\n");
    	
    	printf("column=");
    	scanf("%d",&column);
    	printf("\n");
    	
    	printf("array[%d][%d]\n",row,column);
    	
    	array=(int *)malloc(row*column*sizeof(int));
    	
    
    	count=0;
    	
    	for(i=0;i<row;i++){
    		for(j=0;j<column;j++)
    			array[(i*4)+j]=count++; 
    	}
    	
    	for(i=0;i<row;i++){
    		for(j=0;j<column;j++)
    			printf("%d ",array[(i*4)+j]);
    		printf("\n");
    	}
    	
    	free(array);
    	
    	return 0;
    }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    22,269
    Provide a function to do the index computation for you?
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    The superhaterodyne twomers's Avatar
    Join Date
    Dec 2005
    Location
    Ireland
    Posts
    2,262
    Yeah. Consider that an int* can create a 1D array of ints. So you could conceive of dynamically allocating an array of int*'s from an int**. Then in turn you could allocate an array of ints from each int*.

    That means you need many malloc calls (numRows*numColls), which isn't great. However, for an N-dimensional array you only need N dynamic memory calls. Here's how Salem suggests to do it, in C++. All that you need to know is that new dynamically allocates memory, much like malloc, and delete[] deletes the allocated memory, like free. Then you can access elements via: mBuffer[y][x] very easily.

  4. #4
    Registered User
    Join Date
    Apr 2008
    Posts
    395
    Some notes (unrelated to the question ;-)
    - compile with warnings enabled (your compiler would have said you need stdlib.h too for malloc/free)
    - but in fact you don't need malloc/free here, c99 allows local arrays of dynamic length, this makes things simpler:
    Code:
    #include<stdio.h>
    
    int main(void) {
            // int *array; no longer needed
            int column,row;	
            ...	
    	printf("array[%d][%d]\n",row,column);
    	
    	int array[row*column];
            ...
    	// free(array); no longer needed
    	return 0;
    }
    you can also use array[row][column] and thus array[i][j] later in your code.
    Last edited by root4; 12-31-2008 at 09:59 AM.

  5. #5
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,058
    Quote Originally Posted by lvl99 View Post
    This my attempt at creating a dynamic 2d array. I am able to store the values into the array and read them out. Is there a more elegant way of inputing the values?

    Code:
    array[(i*4)+j]=count++;
    instead of having to multiplying i*4.
    Why use 2D notation for initializing the array when the array is really 1D.
    You could use just one loop to intialize all the elements of the array as in.
    Code:
    for (i = 0; i < row*column; i++)
        array[i] = count++;

  6. #6
    Registered User
    Join Date
    Dec 2008
    Posts
    15
    Thanks for the feedback guys.
    Provide a function to do the index computation for you?
    I'll probably do that.

    Why use 2D notation for initializing the array when the array is really 1D.
    You could use just one loop to initialize all the elements of the array as in.
    Well, eventually I would like to write a program that can do matrix math, like finding the transpose, inverse and stuff like that. The initialization was used for testing.

    - compile with warnings enabled (your compiler would have said you need stdlib.h too for malloc/free)
    - but in fact you don't need malloc/free here, c99 allows local arrays of dynamic length, this makes things simpler:
    I was getting warnings but I ignored them, since they weren't errors. When I add stdlib.h the warnings disappeared.

    Yeah. Consider that an int* can create a 1D array of ints. So you could conceive of dynamically allocating an array of int*'s from an int**. Then in turn you could allocate an array of ints from each int*.
    I'm sorry I couldn't really follow what you were saying. Is there another link that you can direct me to? Also, what does int** do?

    Thanks, again.

  7. #7
    cas
    cas is offline
    Registered User
    Join Date
    Sep 2007
    Posts
    993
    I was getting warnings but I ignored them, since they weren't errors.
    This is not recommended. C itself makes no distinction between warnings and errors. Thus what you consider just a warning can be a direct violation of C's rules. In such a case your compiler is simply choosing to do something it considers reasonable, but is not necessarily the way any other compiler might do it (alternatively, another compiler might consider the problem an error, not a warning).

    All warnings of a good compiler should be paid attention to, whether or not your program compiles, and whether or not your program seems to run fine. Sometimes the result of code that causes a warning is a program that runs fine on your system, but fails on other systems. A real example is a program that assumes ints and pointers are the same size. They are on many systems, but a lot of modern 64-bit compilers have 32-bit ints and 64-bit pointers; so such an assumption breaks there. This, incidentally, is a problem directly related to the failure to include stdlib.h when using malloc().

    For the record, I consider gcc to be a "good compiler" when invoked thus:
    Code:
    gcc -Wall -Wno-missing-braces -std=c99 -pedantic
    Warnings from a gcc invoked like this are almost always worth looking at. If you're targeting POSIX, add -D_XOPEN_SOURCE=600 as well.

    If you're using C89, then -std=c89 can be used instead of -std=c99. If you don't know what this means, I would recommend C99; others may not.

  8. #8
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,273
    Quote Originally Posted by itCbitC View Post
    Why use 2D notation for initializing the array when the array is really 1D.
    You could use just one loop to intialize all the elements of the array as in.
    Code:
    for (i = 0; i < row*column; i++)
        array[i] = count++;
    Yes, but only because the initialization pattern is amenable to that. Often times, it is not.

    If the values being initialized depend on the row and column somehow, but you still want to trace linearly through the array, you can do this:

    Code:
    int i, j, n;
    n = 0;
    for(j = 0; j < numRows; j++)
    {
        for(i = 0; i < numCols; i++, n++)
        {
            array[n] = someFunctionOf(i, j);
        }
    }
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  9. #9
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    23,012
    Quote Originally Posted by lvl99 View Post
    I'm sorry I couldn't really follow what you were saying. Is there another link that you can direct me to? Also, what does int** do?

    Thanks, again.
    int** is just a pointer to int*. Nothing special.
    A common way of creating a 2D array is basically first creating a pointer-to-pointer, which points to an array of pointers, which in turn points to another array of data (say, in this case, int):

    Code:
    int**:
        0: int*:
               0: int
               1: int
               2: int
               etc
        1: int*
        2: int*
        etc
    It gives you a dynamic 2D array. If you wish, it is also possible to do it like this:
    Code:
    int (*p)[20] = malloc(rows * columns * sizeof(T));
    20 being the number of columns.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. put matrix from file into 2d dynamic array
    By meriororen in forum C Programming
    Replies: 3
    Last Post: 06-08-2009, 08:51 AM
  2. from 2D array to 1D array
    By cfdprogrammer in forum C Programming
    Replies: 17
    Last Post: 03-24-2009, 11:33 AM
  3. Allocating a 2D Array Differently
    By pianorain in forum C++ Programming
    Replies: 13
    Last Post: 12-15-2005, 02:01 AM
  4. 2D dynamic array problem
    By scsullivan in forum C Programming
    Replies: 3
    Last Post: 12-30-2002, 10:02 PM
  5. how to pass 2D array into function..?
    By IngramGc in forum C++ Programming
    Replies: 2
    Last Post: 10-21-2001, 09:41 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21