chatay
chatay

Reputation: 164

I can not allocate memory in an array

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

int crp(int mtrs[],int size)
{
    int a=1;
    int i;

    for(i=0;i<size;++i)
    {
        a*=mtrs[i];
    }

    return a;
}

int main()
{
    int k,size;
    int **mtrs;

    printf("enter the size of the matrix:");
    scanf("%d",&size);

    mtrs=(int**)malloc(size*sizeof(int*));

    if( mtrs == NULL )
        printf( "Yetersiz bellek!" );

    printf("enter the input numbers of matrix:");

    for(k=0;k<size;k++)
    {
        mtrs[k] =(int*) malloc( size* sizeof(int) );
        if( mtrs[k] == NULL )
            printf( "not enough memory!" );
    }
    for(k=0;k<size;k++) 
    {
        scanf("%d",&mtrs[k]);
    }
    printf("\n\n");

    for(k=0;k<size;k++){
        printf("%d ",mtrs[k]);
    }

    printf("\n\n");
    printf("Elemanlar carpimi %d dir.",crp(mtrs[k],size));

    return 0;
}

I get the problem of access violation reading location 0xFDFDFD.

it stucks at the location of a*=mtrs[i];.. The program's aim is to multiplication of the entered numbers

I am not sure if I am using the malloc in a correct way.

Upvotes: 1

Views: 90

Answers (2)

Inline
Inline

Reputation: 2843

I do not fully understand what is your code point, but you have various mistakes and logic problems with it.

  1. printf("%d ",mtrs[k]); and scanf("%d",&mtrs[k]); expect int but you passed *int (aka int[]), you probably need to insert/read values using 2 nested for loops.
  2. printf("Elemanlar carpimi %d dir.",crp(mtrs[k],size)); last cycle is for(k=0;k<size;k++), according to it k = size, so mtrs[k] is out of bounds, which cause application crash.

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310910

This code snippet is invalid

for(k=0;k<size;k++) 
{

    scanf("%d",&mtrs[k]);
               &&&&&&&&
}

You should write for example

int m;
//...

for(k=0;k<size;k++) 
{
    for ( m = 0; m < size; m++ )        
    {
        scanf("%d", &mtrs[k][m]);
    }
}

The same is valid for this loop

for(k=0;k<size;k++){


    printf("%d ",mtrs[k]);

}

It should look like

for(k=0;k<size;k++) 
{
    for ( m = 0; m < size; m++ )        
    {
        printf("%d ",mtrs[k][m]);
    }
    printf( "\n" );
}

The function should be defined like

long long int crp( int * mtrs[],int size)
^^^^^^^^^^^^^      ^^^^^^^^^^^^
{
    long long int a=1;
    int i, j;
    ^^^^^^^^^


    for(i=0;i<size;++i)
    {
        for ( j = 0; j < size; j++ )
        {
            a*=mtrs[i];
        }
    }

    return a;
}

And the result of the function should be outputted like

printf("Elemanlar carpimi %lld dir.",crp(mtrs,size));
                          ^^^^^

Upvotes: 1

Related Questions