user3460758
user3460758

Reputation: 987

Manipulating struct in C - inputting variables

I'm trying to write a small portion of a larger code that will ultimately input a struct and use the values inputted to do some volume calculations of a boat. I'm trying to create a struct and then in my function (at the moment I have no function and I'm just calling it from my main), I want to give the struct values. As the eventual volume calculations are really long, I'm trying to avoid using something like "new_boat.L1" every time I need to use the L1 value. To do this, I'm using the following code:

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>

struct boat {
    double L1;
    double L2;
    double Lhull;
    double C;
    double delta;
    double mass;
};



int main() {
    // make two people structures
    struct boat new_boat; 
    double L1, L2, C;

    new_boat.L1 = L1;
    new_boat.L2 = L2;
    new_boat.C = C;

    L1 = 17.6;
    L2 = 4;
    C = sqrt((new_boat.L1*new_boat.L1) + (new_boat.L2*new_boat.L2));


    printf("\nL1 = %lf\n L2 = %lf\n, C = %lf\n", L1, L2, C);


    return 0;

    }

The values I'm trying to input for L1, L2, and C are not being passed into the structure and I wasn't sure exactly how to do that so these values will be saved and can be used and called later by their shorter names. Hope this explanation makes sense! Any help would be really appreciated. Thanks in advance!

Upvotes: 0

Views: 107

Answers (3)

Jimm
Jimm

Reputation: 31

Assignments are done by value, not by variable. When you're assigning new_boat.L1 = L1, for example, you haven't set L1 to anything yet.

Try setting L1, L2, and C before assigning new_boat:

L1 = 17.6;
L2 = 4;
C = sqrt((L1*L1) + (L2*L2));

new_boat.L1 = L1;
new_boat.L2 = L2;
new_boat.C = C;

Upvotes: 0

Kyew
Kyew

Reputation: 33

new_boat.L1 = L1;
new_boat.L2 = L2;
new_boat.C = C;

When you do that, you're not making the local variables reference the structure variables. You are copying the local variables values into your structure variables.

If you want to reference the structure variable you can use pointers, that will point on your structure variables. Like this :

struct boat new_boat; 
double *L1, *L2, *C;

L1 = &new_boat.L1;
L2 = &new_boat.L2;
C = &new_boat.C;

*L1 = 17.6;
*L2 = 4;
*C = sqrt((*L1) * (*L1) + (*L2) * (*L2));

Hope this helps you.

Upvotes: 0

Jabberwocky
Jabberwocky

Reputation: 50831

You don't initialize L1, L2 and C. They contain garbage and therefore new_boat will contain garbage as well.

This version should work as expected:

int main() {
// make two people structures
  struct boat new_boat; 
  double L1, L2, C;

  L1 = 17.6;
  L2 = 4;
  C = sqrt((L1*L1) + (L2*L2));

  new_boat.L1 = L1;
  new_boat.L2 = L2;
  new_boat.C = C;

  printf("\nL1 = %lf\n L2 = %lf\n, C = %lf\n", L1, L2, C);

  return 0;
}

Upvotes: 1

Related Questions