0

Hello I have a problem when I call to function arrayBigToSmall the program crashes (after I enter the numbers). I want to understand why this happens and how I can fix this problem.?

Code -

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

    int main()
    {
    float array[2][3][2];
    getNums(array);
    return(0);
    }

    void getNums(float array[2][3][2])
    {
    int i,j,p;

    printf("Enter numbers: \n");
    for(i = 0; i < 2 ; i++)
    {
        for(j = 0; j < 3; j++)
        {
            for(p = 0; p < 2; p++)
            {
                scanf("%f",&array[i][j][p]);
            }
        }
    }
    arrayBigToSmall(array);
    }

    void arrayBigToSmall(float array[2][3][2])
    {

    int i,j,p,k;
    float array1[12];
    float temp;

    for( i=0; i<3; i++)
    {
        for( j=0; j  < 2; j++)
        {
            for(p = 0; p < 3; p++)
            {
                array1[k] = array[i][j][p];
                k++;
            }
        }
    }
    }
1
  • 5
    you failed to initialize k in arrayBigToSmall(). Your compiler would have told you if you compiled with all warnings enabled. Commented Apr 6, 2014 at 9:06

2 Answers 2

4
for( i=0; i<3; i++)
{
    for( j=0; j  < 2; j++)
    {
        for(p = 0; p < 3; p++)
        {
            array1[k] = array[i][j][p];
            k++;
        }
    }
}
}

k must be initialized to 0. i should be not greater than 2, j not greater that 3, and p not greater than 2

Sign up to request clarification or add additional context in comments.

Comments

2

Be careful with size of array use following: as the dimension of your array is 2 x 3 x 2 but in your code you are using 3 loops in 3 x 2 x 3 manner which overflows and which result in crash . Also you should intialise k before using it.

void arrayBigToSmall(float array[2][3][2])
{

int i,j,p,k=0;
float array1[12];
float temp;

for( i=0; i<2; i++)
{
    for( j=0; j  < 3; j++)
    {
        for(p = 0; p <2 ; p++)
        {
            array1[k] = array[i][j][p];
            k++;
        }
    }
}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.