Thread: C 2D arrays
View Single Post
Old 1st August 2008
ephemera's Avatar
ephemera ephemera is offline
Knuth's homeboy
 
Join Date: Apr 2008
Posts: 537
Default

here's a program to get you started:

Code:
#include <stdio.h>
#include <stdlib.h>

int main()
{
        int **a, row_size, col_size, i;

        row_size = 1000;
        col_size = 1000;

        a = malloc(row_size * sizeof(int *));
        if (NULL == a) {
                perror("malloc");
                exit(1);
        }
        for (i = 0; i < row_size; i++) {
                a[i] = malloc(col_size * sizeof(int));
                if (NULL == a[i]) {
                        perror("malloc");
                        exit(1);
                }
        }
        return a[row_size - 1][col_size - 1] = 53;
}
Compile with the gcc compiler:
$ cc -Wall -g prog.c

Check if it worked:
$ echo $?

(note: in a real world program you will want to free(3) the pointers to avoid a memory leak.)

Last edited by ephemera; 2nd August 2008 at 06:52 AM.
Reply With Quote