Thread: Arrays

  1. #1
    Registered User
    Join Date
    Apr 2020
    Posts
    62

    Arrays

    How do I make a dynamic 2d array in C with malloc realloc and free?

  2. #2
    Registered User
    Join Date
    Aug 2019
    Location
    inside a singularity
    Posts
    308
    (1) You can google to find out.

    (2) You can use a 1D array (as 2D arrays and 1D arrays are fundamentally the same thing). You just need to do access arithmetic yourself, which is not something hard.

    (3) You can use an array of pointers and allocate memory of appropriate size for each.

    (4) You can use a double pointer method which is similar to using (2) and (3) together.

    I don't know of any other methods, if any.
    "Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning." - Rick Cook, The Wizardry Compiled

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    The malloc and free of arrays, in various ways.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    void f1(void) {
      int a[10];
      int *b = malloc(10*sizeof(*b));
      ///
      free(b);
    }
    
    // If the minor dimension is always fixed
    void f2(void) {
      int a[10][20];
      int (*b)[20] = malloc(10*sizeof(*b));
      ///
      free(b);
    }
    
    // variable in both dimensions
    void f3(void) {
      int a[10][20];
      int **b = malloc(10*sizeof(*b));
      for( int i = 0 ; i < 10 ; i++ )
        b[i] = malloc(20*sizeof(*b[i]));
      ///
      for ( int i = 0 ; i < 10 ; i++ )
        free(b[i]);
      free(b);
    }
    
    // variable in both dimensions, but all rows the same
    void f4(void) {
      int a[10][20];
      int **b = malloc(10*sizeof(*b));
      b[0] = malloc(10*20*sizeof(*b[0]));
      for( int i = 1 ; i < 10 ; i++ )
        b[i] = b[i-1] + 20;
      ///
      free(b[0]);
      free(b);
    }
    
    int main ( ) {
      f1();
      f2();
      f3();
      f4();
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 02-06-2014, 02:39 PM
  2. Replies: 9
    Last Post: 07-11-2013, 10:57 PM
  3. Replies: 16
    Last Post: 01-01-2008, 04:07 PM
  4. Replies: 2
    Last Post: 02-23-2004, 06:34 AM
  5. separating line of arrays into array of arrays
    By robocop in forum C++ Programming
    Replies: 3
    Last Post: 10-20-2001, 12:43 AM

Tags for this Thread