1

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

1

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();
}
dbush
  • 205,898
  • 23
  • 218
  • 273
  • This will _probably_ work, (if [IEEE 754](https://stackoverflow.com/a/8558852/2472827).) If you want to be sure, loop through and set then to zero manually. – Neil May 14 '20 at 21:33