[Solved] Error in code, programming in C


You need to allocate an array of vectors, using malloc.

typedef struct
{
    float x;
    float y;
}vectors;

vectors initializeVector(vectors userVect[], int length);

int main()
{
    /* This block determines the amount of vectors that will be added.
    It will then create an array of vector structs the size of the amount being added.
    Afterwards it will call a function that will grab the users data (vector information) and use
    to add the vectors in the array.*/

    int amount;
    printf("How many vectors would you like to add?\n");
    printf("Count: ");
    scanf("%d", &amount);
    if(amount<1) { printf("error, need vector size %d > 0\n",amount); exit(1); }
    vectors *vectarray = malloc(sizeof(vectors)*amount); //allocate the vector for the given vector size
    if(!vectarray) { printf("error, cannot allocate vectorarray[%d]\n",amount); exit(2); }
    initializeVector(vectarray,amount); //<-- This is a function call.
    return 0;
}

Then you need to pass that array (as a pointer) to the initializer, and you need to provide the address of your x,y components, not just the components.

vectors initializeVector(vectors userVect[], int length) //pass an array
{
    /* This function will go through the array of vectors and allow the user
    to input the components of each vector in the array.*/

    printf("Enter the 'X' and 'Y' components of your vector\n");
    int i;
    for(i=0; i<length;i++)
    {
        printf("%d", i+1);
        printf(" vector:\n");
        printf("X: ");
        scanf("%f", &(userVect[i].x)); //scanf wants a pointer to the x component
        printf("\nY: ");
        scanf("%f", &(userVect[i].y)); //scanf wants a pointer to the y component
    }
}

1

solved Error in code, programming in C