HaggarTheHorrible HaggarTheHorrible - 1 year ago 87
C Question

Use #define to define an array size

I used to capture 5 seconds of data from an ADC which was sending samples at 125 SPS, this translated to having an array of size 5 * 125. In my code this looked like:

#define SPS 125
#define TIME 5

char Samples[SPS * TIME];

Now, I would like to capture 2.5 seconds of data and increase the ADC sampling rate to 250 SPS. In the code it looks like:

#define SPS 250
#define TIME 2.5

char Samples[SPS * TIME];

But if I do this the compiler throws up an error as:

#901 expression must have integral or enum type main.cpp line 59 C/C++ Problem

I'm able to understand what it is saying.

But what is the best way to overcome this situation keeping the SPS and TIME definition's usability in mind. I mean I've used them in several other places across the project and I wish to keep using them as they are.

Kindly help!

Answer Source

The problem is that the result is converted to a float ( or double ), but the size of an array must be an integral type. The easiest solution would be as suggested by @CoolGuy, you can cast it to an int. Here is an example

#define SPS 125
#define TIME 2.5

char Samples[ (int)(SPS * TIME) ];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download