Lavi
Lavi

Reputation: 1

Thread 1: EXC_BAD_ACCESS (code=1, address=0x0) Xcode

I am running this code on Xcode version 11.2 . I have a matrix with 5 rows and 3 colomns and I want to calculate the average value of each row. Now here I tried to code it, but my matrix seems to be always null and I get this error Thread 1: EXC_BAD_ACCESS (code=1, address=0x0) at s= s +aloc[i*5+j];. I don't know what I should modify at my code so it works. Can you help me?

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

void  reads(float  *aloc);
void amount(float  *aloc);
void done(float *aloc);

int  main()
{

        float  *aloc  =  NULL;


    reads(aloc);
    amount(aloc);
    done(aloc);

        return  0;
}

void  reads(float  *aloc)
{
               if  ((aloc  =  (float*)malloc(5  *  sizeof(float))))
        {

                for  (int  i  =  0;  i  <  5;  i++)
                {
                     printf("\n  Enter  the values for the row no. %d  :  ",1+i);
                    for(int j=0;j<3;j++)
                        scanf("%f",  aloc  +  i*5+j);
                }
        }
}

void amount(float  *aloc)
{
    float s;
    int j,i;

           for(i=0;i<5;i++)
           { s=0;
         for(j=0;j<3;j++)

            s= s +aloc[i*5+j];

            printf("\n The average of the row no. %d is : %.2f ",i+1,s/3.);

           }
}

void done(float *aloc)
{
     free(aloc);
}

Upvotes: 0

Views: 648

Answers (1)

Ghii Velte
Ghii Velte

Reputation: 125

reads() only allocates space for 5 floats -- which is only one column or row of your matrix.

Change:

aloc  =  (float*)malloc(5  *  sizeof(float))

to:

aloc = malloc( 5 * 3 * sizeof(float))

Upvotes: 2

Related Questions