C - allocating a matrix in a function

I am trying to allocate a matrix using a function that takes its dimensions and a triple pointer. I have allocated an int** (set to NULL) and I am passing its address as the function's argument. That gives me a mem access violation for some reason.

void allocateMatrix(int ***matrix, int row, int col)
{
    int i;
    if((*matrix = (int**)malloc(row * sizeof(int*))) == NULL)
    {
        perror("There has been an error");
        exit(EXIT_FAILURE);
    }
    for(i = 0; i < row; ++i)
    {
        if((*matrix[i] = (int*)malloc(col * sizeof(int))) == NULL)
        {
            perror("There has been an error");
            exit(EXIT_FAILURE);
        }
    }
}

/* main.c */

    int** matrix = NULL;
    allocateMatrix(&matrix, MATRIX_ROW, MATRIX_COL); //error

Answers


You need to change

if((*matrix[i] = (int*)malloc(col * sizeof(int))) == NULL)

to

if(((*matrix)[i] = (int*)malloc(col * sizeof(int))) == NULL)
//  ^       ^

You need to dereference matrix before using the array subscript. *matrix[i] is equivalent to *(matrix[i])


It's a problem of operator precedence. In

if ((*matrix[i] = (int*)malloc( ... ))

the default precedence is *(matrix[i]), while you should use (*matrix)[i].

I would still recommend to allocate the matrix as a contiguous array instead as a array of pointers to arrays.


Need Your Help

Javascipt how to stop the valid true pop up after click the ok alert

javascript popup

How can I stop this from popping up after clicking the OK alert? (Your answer is correct). After clicking OK, the below image pops up.

Calculator Algorithm - Using Iteration instead of Recursion on Binary Search Tree

java algorithm recursion binary-tree

I've seen approaches on how to iterate through binary trees and find the sum of all nodes, except I'm evaluating expression inputs for a calculator. The nodes are arranged in the proper order accor...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.