Search code examples
cscanf

scanf fails to add data to a struct?


I'm writing a program to add two vectors, I've defined two structs like so:

typedef struct TwoDVector {
    float x_coord;
    float y_coord;
} vec_2d;

typedef struct VectorAddData {
    float x_coord;
    float y_coord;
    float magnitude;
} vec_data;

Then in my code I run a loop to add data:

vec_data add_vectors(vec_2d vec1, vec_2d vec2) {
    vec_data final_vec;
    final_vec.x_coord = vec1.x_coord + vec2.x_coord;
    final_vec.y_coord = vec1.y_coord + vec2.y_coord;
    final_vec.magnitude = sqrt(pow(final_vec.x_coord, 2) + pow(final_vec.y_coord, 2));

    return final_vec;
}

int main(void){
    while (1) {
        int choice;
        printf("Press 1 to add two vectors(2D)\nPress 0 to quit: ");
        scanf_s("%d", &choice);
        if (choice == 1) {
            vec_2d vec1, vec2;
            vec_2d arr[] = {vec1, vec2};
            for(int i = 0; i<2; i++) {
                printf("Enter values for vector %d\n", i + 1);
                printf("Enter x_coord for vector %d: ", i + 1);
                scanf_s("%f", &arr[i].x_coord);
                printf("Enter y_coord for vector %d: ", i + 1);
                scanf_s("%f", &arr[i].y_coord);
            }
            printf("\nAdding the 2 vectors...\nVec1 = %fi + %fj \t vec2 = %fi + %fj\n", vec1.x_coord, vec1.y_coord, vec2.x_coord, vec2.y_coord);
            vec_data final_vec = add_vectors(vec1, vec2);
            printf("Addition of 2 vectors = %fi + %fj\n", final_vec.x_coord, final_vec.y_coord);
            printf("Magnitude of final vector: %f\n", final_vec.magnitude);

        } else if (choice == 0) {
            break;
        } else {
            printf("Invalid input!");
        }
    }   

    return 0;
}

But as I enter values, the code only returns x and y coordinates as 0.000, what am I doing wrong, I've written this code standalone before.


Solution

  • you're putting the values into arr but reading from vec1, vec2

    when you do vec_2d arr[] = {vec1, vec2}; you're copying the values from vec1, vec2 into a new array called arr. If you want arr to point to vec1 and vec2 you should do:

    vec_2d *arr[] = {&vec1, &vec2};
    

    and then:

    printf("Enter x_coord for vector %d: ", i + 1);
    scanf_s("%f", &arr[i]->x_coord);
    printf("Enter y_coord for vector %d: ", i + 1);
    scanf_s("%f", &arr[i]->y_coord);