Home > OS >  Why my code runs up to point A and crashes when I give B coordinates?
Why my code runs up to point A and crashes when I give B coordinates?

Time:07-09

I am new at C pointers and I'm trying to find the error. Any help is appreciated. The code compiles without any errors. When it runs, it accepts point A coordinates but crashes when I input B coordinates. The output I get is this:

Give Coordinates...
Give A(x1,y1): 
2
3
Give B(x2,y2): 
4
zsh: bus error  ./a.out
andreas@Andreas % 

Code:

#include <stdlib.h>

struct point
{
    int x;
    int y;
};

struct triangle
{
    struct point *A;
    struct point *B;
    struct point *C;
};

void initialiseTriangle(struct triangle *);

int main()
{
    system("clear");

    struct triangle triangle1, *trianglePtr;
    trianglePtr = &triangle1;
    
    initialiseTriangle(trianglePtr);
    return 0;
}

void initialiseTriangle(struct triangle *object)
{
    printf("Give Coordinates...\n");
    printf("Give A(x1,y1): \n");
    scanf("%d", &object->A->x);
    scanf("%d", &object->A->y);

    printf("Give B(x2,y2): \n");
    scanf("%d", &object->B->x);
    scanf("%d", &object->B->y);

    printf("Give C(x3,y3): \n");
    scanf("%d", &object->C->x);
    scanf("%d", &object->C->y);
}```>quote



CodePudding user response:

It is because you allocate space for the triangle, but not for the point pointers.

You could either allocate memory (here on the stack) :

int main()
{
    system("clear");

    struct triangle triangle1, *trianglePtr;
    struct point pointA, pointB, pointC;
    triangle1.A = &pointA;
    triangle1.B = &pointB;
    triangle1.C = &pointC;
    trianglePtr = &triangle1;
    
    initialiseTriangle(trianglePtr);
    return 0;
}

or directly put the point structs into the triangle struct, instead of using pointers :

struct triangle
{
    struct point A;
    struct point B;
    struct point C;
};
  • Related