Welcome to the Parallax Discussion Forums, sign-up to participate.

Simple C Coding Question

Posts: 126
Hello,

I am trying to get the following code to print d = f.
```float phi = 0;
float theta = 0;
float gx = 10;
float gy = 5;
float gz = 1;

float f[2][1] = {
{gx+gy*sin(phi)*tan(theta)+gz*cos(phi)*tan(theta)},
{gy*cos(phi)-gz*sin(phi)}
};

float d[2][1] = {f[2][1]};
```

f is a 2x1 vector equal to [10,5]'. However, when I print d it just gives me [0,0]'. d should be the same as f. What am I doing wrong in that last line of code?

Thanks,
David

• Posts: 2,706
The line:
```float d[2][1] = {f[2][1]};
```

is not doing what you think it does. "f[2][1]" is a specific element of "f", not the whole array. So you are creating a two element array and initializing it with only one element.

Worse, it is an undefined element. F was declared as
```float f[2][1] = {...};
```
so the only legal references to f are "f[0][0]" and "f[1][0]", so "f[2][1]" is undefined.
• Posts: 126
Hello ersmith,

Thank you for your reply. Now I understand why it's not working but I'm still not sure how to fix it. The reason I want to do this is so I can multiply the array by a scalar value. So what I want to be able to do is something like this:
```float d[2][1] = .001 * {f[2][1]};
```

Thanks,
David
• Posts: 2,706
Hello ersmith,

Thank you for your reply. Now I understand why it's not working but I'm still not sure how to fix it. The reason I want to do this is so I can multiply the array by a scalar value. So what I want to be able to do is something like this:
```float d[2][1] = .001 * {f[2][1]};
```

Thanks,
David

C doesn't work that way -- it does not allow multiplication of an array by a scalar (I think Fortran does, but C doesn't). You'll have to do it at run time in a loop, something like:
```int i;
...
for (i = 0; i < 2; i++) {
d[i][0] = .001 * f[i][0];
}
```
Which also raises an interesting point; why did you declare the arrays as two dimensional (like f[2][1]) when the second dimension only has one possible value? It would be simpler to write just f[2]:
```float f[2] = { ... }
float d[2];
int i;
...
for (i = 0; i < 2; i++) {
d[i] = .001 * f[i];
}
```

Eric
• Posts: 126
Hi Eric,

I just wanted to thank you for your help. Your response got me going to the next step in my coding project. I am trying to implement an extended Kalman filter to estimate roll and pitch. Once I hopefully get it working I will post the code on the forums to give back.

Regards,
David