Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Having trouble calling two functions from a structure, no logic error.

+2 votes
asked Sep 16, 2022 by Bob (140 points)
#include <iostream>
#include <cmath>
using namespace std;
struct Point3D {
    int x;
    int y;
    int z;
};

Point3D AddTwoPoints(Point3D a, Point3D b)
{
float c2.x = b.x + a.x;    /*outputs error expected initializer before '.' token
float c2.y = b.y + a.y;
float c2.z = b.z + a.z;      */
return;
}
Point3D SubtractTwoPoints(Point3D a, Point3D b) {
float d2.x = b.x - a.x;    /*outputs error expected initializer before '.' token
float d2.y = b.y - a.y;
float d2.z = b.z - a.z;      */
return;
}

int main()
{
    Point3D a2, b2;
    a2.x = 4;
    a2.y = 7;
    a2.z = -14;
    b2.x = 5;
    b2.y = 5;
    b2.z = 10;

Point3D c2 = AddTwoPoints(a2, b2);
    cout << "Add a2 and b2: (" << c2.x << "," << c2.y << "," << c2.z << ")" << endl;  
    Point3D d2 = SubtractTwoPoints(a2, b2);
    cout << "Subtract b2 from a2: (" << d2.x << "," << d2.y << "," << d2.z << ")" << endl;  
    return 0;
}

1 Answer

+1 vote
answered Sep 16, 2022 by Peter Minarik (86,160 points)

You're using c2.x for a variable name. Variable names cannot contain a dot (.). You can use underscore (_) or just call your variables x, y, z instead. :)

Another solution is to return a new Point3D and initialize it while you return it:

Point3D AddTwoPoints(Point3D a, Point3D b)
{
    return Point3D { a.x + b.x, a.y + b.y, a.z + b.z };
}

Point3D SubtractTwoPoints(Point3D a, Point3D b)
{
    return Point3D { a.x - b.x, a.y - b.y, a.z - b.z };
}
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...