Gonçalo Costa
Gonçalo Costa

Reputation: 23

How do I properly create a matrix in C with malloc?

So, I wrote this C function that receives an integer n and is supposed to create a matrix with n lines and n + 1 columns.

The problem that I'm facing right now is that all the values in the column n (last column) are not initialized as 0.0, unlike all the other seeds from the matrix.

Here is my code:

float** createMatrix(int n){
    float **matrix;
    int numLines = n;
    int numCol = n + 1;

    matrix = (float**) malloc(numLines*sizeof(float *));
    if(matrix == NULL) abort();

    for(int i = 0; i < numLines; i++){
        matrix[i] = (float*) malloc(numCol * sizeof(float));
        if (matrix[i] == NULL)
            abort();
    }

    return matrix;
} 

Would really appreciate some help. I've been stuck on this bug for a while now.

Upvotes: 1

Views: 122

Answers (1)

dbush
dbush

Reputation: 223972

The memory returned from malloc is not initialized. Each byte can contain any value.

You can instead use calloc which initializes all bytes to 0.

for(int i = 0; i < numLines; i++){
    matrix[i] = calloc(numCol, sizeof(float));
    if (matrix[i] == NULL) abort();
}

Upvotes: 1

Related Questions