0

I am a beginner at using C. I have program that takes two vectors, finds their difference as a vector and computes its length. I am trying to generalise it so that any vectors of any size can be put in without any other change. I find an issue when trying to input the size of the vector into the external function, modulus. It will print off random numbers in the correct format, mostly zero, so the true error is unclear. What am I doing wrong?

int i, l;

float modulus(float vec[], int length);
void main() {
  /* declare and initialise a position vector */
  float positionVector1[] = {6.0, 3.0};
  float positionVector2[] = {3.0, 2.0};
  int L = sizeof(positionVector1);
  float positionVector[L];
  for (i = 0; i < L; i++) {
    positionVector[i] = positionVector2[i] - positionVector1[i];
  }
  float len;
  len = modulus(positionVector, L);
  printf("length is %.2e\n", len);
}

float modulus(float vec[], int length) {
  float mod = 0.0;
  for (i = 0; i < length; i++) {
    mod = mod + (vec[i] * vec[i]);
  }
  mod = sqrt(mod);
}
Eraklon
  • 4,206
  • 2
  • 13
  • 29
  • 1
    `sizeof X` tells you how many *bytes* are in `X`, not how many elements. (And it works on any object, not just arrays.) – rici Mar 29 '20 at 18:30
  • 2
    Does this answer your question? [How do I determine the size of my array in C?](https://stackoverflow.com/questions/37538/how-do-i-determine-the-size-of-my-array-in-c) – Blastfurnace Mar 29 '20 at 18:36

0 Answers0