wicwik - 1 month ago 7
C Question

# Endless loop in C when filling 2D array with for

Hey I need some help I am trying to make a determinant to multyply 2 vectors this is my code:

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

void determinantAxB();

int main()
{

int i;
float a[2],b[2],abzlozky[2],c[2],d[2],cdzlozky[2];

for (i = 0; i < 3; i++)
{
if (i == 0)
{
printf("\nx=");
scanf("%f",&a[0]);
}
if (i == 1)
{
printf("y=");
scanf("%f",&a[1]);
}
if (i == 2)
{
printf("z=");
scanf("%f",&a[2]);
}
}

for (i = 0; i < 3; i++)
{
if (i == 0)
{
printf("\nx=");
scanf("%f",&b[0]);
}
if (i == 1)
{
printf("y=");
scanf("%f",&b[1]);
}
if (i == 2)
{
printf("z=");
scanf("%f",&b[2]);
}
}

for (i = 0; i < 3; i++)
{
abzlozky[i] = b[i] - a[i];
}

for (i = 0; i < 3; i++)
{
if (i == 0)
{
printf("\nx=");
scanf("%f",&c[0]);
}
if (i == 1)
{
printf("y=");
scanf("%f",&c[1]);
}
if (i == 2)
{
printf("z=");
scanf("%f",&c[2]);
}
}

for (i = 0; i < 3; i++)
{
if (i == 0)
{
printf("\nx=");
scanf("%f",&d[0]);
}
if (i == 1)
{
printf("y=");
scanf("%f",&d[1]);
}
if (i == 2)
{
printf("z=");
scanf("%f",&d[2]);
}
}

for (i = 0; i < 3; i++)
{
cdzlozky[i] = d[i] - c[i];
}

printf("Vektor AB= %6.3fi, %6.3fj, %6.3fk",abzlozky[0],abzlozky[1],abzlozky[2]);
printf("\nVektor CD= %6.3fi, %6.3fj, %6.3fk",cdzlozky[0],cdzlozky[1],cdzlozky[2]);

getch();

determinantAxB(abzlozky[2],cdzlozky[2]);

getch();
return 0;
}

void determinantAxB(float ab[2],float cd[2])
{
int j,k;
float vypocet[1][2];

for (j = 0; j < 2; j++)
{
for (k = 0; k < 3; k++)
{
if (j == 0) vypocet[j][k] = ab[k];
else vypocet[j][k] = cd[k];
printf("%f",vypocet[j][k]);
}
printf("\n");
}

}
``````

I think the problem is in the function determinantAxB but I cant find the mistake.
In main function I have cordinates of the points x,y,z determined then I take of B - A to calculate parts of vector i,j,k. In function determinantAxB I tryed to put this arrays to one 2D array but I failed. can u help me ?

You need to declare your arrays correctly.

`float a[2];` declares an array of two elements. `a[0]` is the first element, and `a[1]` is the second one. `a[2]` would be the third element, but there are only two. Thus an attempt to access `a[3]` is an out of bounds error and undefined behaviour.

If you want an array of three elements, write `float a[3];`.

On an unrelated note, there is no reason to write a loop to do three unrelated things. Instead of

``````for (i = 0; i < 3; i++)
{
if (i == 0)
{
printf("\nx=");
scanf("%f",&a[0]);
}
if (i == 1)
{
printf("y=");
scanf("%f",&a[1]);
}
if (i == 2)
{
printf("z=");
scanf("%f",&a[2]);
}
}
``````

write just

``````// first thing
printf("\nx=");
scanf("%f",&a[0]);

// second thing
printf("y=");
scanf("%f",&a[1]);

// third thing
printf("z=");
scanf("%f",&a[2]);
``````