Reputation: 17
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++;
}
}
}
}
Upvotes: 0
Views: 67
Reputation: 2576
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++;
}
}
}
}
Upvotes: 2
Reputation: 1447
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
Upvotes: 4