Arduino IDE: array bound - arrays

I get an array bound error in Arduino IDE for the following code. This can be solved if I put the outcome of the calculation for the "sample" (which is 50 in this case) but this is kind of dummy solution. I want the software to do it for myself not me doing hand calculations and insert it. What would be the workaround? Thanks!
int des_freq=200;
int ncycles=5;
int sample =1000/(des_freq*T);
float V_sin_bip[sample]; // error here

As of version 1.6.6, Arduino IDE enables C++11 by default. But C++ standard (till C++11) doesn’t support variable-sized arrays. The C++11 standard mentions array size as a constant-expression.
float V_sin_bip[sample]; uses variable expression to mention array size. Thus, an error occurs.
If you want a "variable-length array" (better called a "dynamically sized array" in C++, since proper variable-length arrays aren't allowed), you either have to dynamically allocate memory yourself:
int n = 10;
double* a = new double[n]; // Don't forget to delete [] a; when you're done!
Or, better yet, use a standard container:
int n = 10;
std::vector<double> a(n); // Don't forget to #include <vector>
If you still want a proper array, you can use a constant, not a variable, when creating it:
const int n = 10;
double a[n]; // now valid, since n isn't a variable (it's a compile time constant)

Related

Are arrays with a defined const allowed in C++?

I tried to run the following code with a C++ compiler:
#include <iostream>
#include <string>
using namespace std;
int MAX=10;
int list[MAX];
int main()
{
int sum =0;
for (int i = 0; i<=MAX; ++i){
list[i]=i;
}
for (int i = 0; i<=MAX; ++i){
sum=sum+list[i];
}
cout << sum << endl;
}
But received this error:
"integer array bound is not an integer constant before ‘]’ token"
I don't understand why this is an error because I have defined MAX as 10 right before
int list[MAX]
so shouldn't it work?
Appreciate any help
No compiler error message here, just exactly what the error message says. You haven't included a const before your int MAX declaration.
Capital letters and never changing the value of MAX doesn't mean it's a constant.
Note that some compilers accept having a variable (i.e. int MAX = 10; instead of const int MAX = 10; for array initialization. Don't rely on this because it shouldn't occur.
If you want to use a variable to initialize an array, you need to use pointers:
int size;
cin >> size;
int *list = new int[size];
I don't understand why this is an error because I have defined MAX as 10 right before int list[MAX]
You defined MAX as 10 but you didn't define MAX as constant. It's an error because the compiler insists that (in this case) the array bound must be an integer constant.
One way to fix the error is to make MAX constant...
const int MAX = 10;
int list[MAX];
Another way to avoid the error is to move the array off the stack and onto the heap (since the bound of a heap array doesn't have to be constant) …
auto list = new int[MAX];
… however this changes the type of list from int[10] to int * and also forces you to become responsible for managing the life of list by calling delete when appropriate (which can be a non-trivial challenge) …
delete [] list;
Not deleting list correctly can cause memory leaks.
You can avoid the error and avoid responsibility for managing the array by using a unique_ptr …
std::unique_ptr<int[]> list{ new int[MAX] };
However many well regarded authorities would argue that using a container like std::vector or std::array would be a better approach. For example, in Effective Modern C++ Scott Meyers says this...
The existence of std::unique_ptr for arrays should be of only intellectual interest to you, because std::array, std::vector, and std::string are virtually always better data structure choices than raw arrays. About the only situation I can conceive of when a std::unique_ptr would make sense would be when you’re using a C-like API that returns a raw pointer to a heap array that you assume ownership of.
At this point you may be wondering why MAX has to be constant in your original code. I'm not a language lawyer but I believe the short answer is because the C++ Standard says it must be so.
For insight into why the standard imposes that requirement you could read some of the answers to the question Why aren't variable-length arrays part of the C++ standard?

Array definition - Expression must have a constant value

I am creating an array on stack as
static const int size = 10;
void foo() {
..
int array[size];
..
}
However, I get the compile error: "expression must have a constant value", even though size is a constant. I can use the macro
#define SIZE (10)
But I am wondering why size marked const causes compilation error.
In C language keyword const has nothing to do with constants. In C language, by definition the term "constant" refers to literal values and enum constants. This is what you have to use if you really need a constant: either use a literal value (define a macro to give your constant a name), or use a enum constant.
(Read here for more details: Shall I prefer constants over defines?)
Also, in C99 and later versions of the language it possible to use non-constant values as array sizes for local arrays. That means that your code should compile in modern C even though your size is not a constant. But you are apparently using an older compiler, so in your case
#define SIZE 10
is the right way to go.
The answer is in another stackoverflow question, HERE
it's because In C objects declared with the const modifier aren't true
constants. A better name for const would probably be readonly - what
it really means is that the compiler won't let you change it. And you
need true constants to initialize objects with static storage (I
suspect regs_to_read is global).
if you are on C99 your IDE compiler option may have a thing called variable-length array (VLA) enable it and you won't get compile error, efficiently without stressing your code though is with MALLOC or CALLOC.
static const int size = 10;
void foo() {
int* array;
array = (int *)malloc(size * sizeof(int));
}

How to create a pre defined variable array in C

I am trying to create an array according to the size that the user inputs but it does not seem to be working for c programming. The following are my codes:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int x, y;
scanf("%d", &x);
scanf("%d", &y);
double arr[x][y];
}
The compiler keeps returning an error of" Error: Expression must have a constant value. at the line double ... could anyone help point out the error?
You have two choices:
Either use a decent C compiler that supports C99 (or later) and variable-length arrays (I'd go with this approach, personally);
or if that is not possible, or the resulting array would be too large to fit in a block-scope variable (causing, for example, a stack overflow), you can use malloc(); however, you won't be able to create a true two-dimensional array using that approach, only a pointer-to-pointer, which may or may not be what you are looking for.
The code can work in C99 mode or when the compiler supports VLA(variable length arrays) as an extension (e.g, GCC supports VLA as GNU extesnion).
In C89, you have to use pointers with dynamic memory to simulate.
Older C standards don't provide support for arrays that do not have compile-time sizes:
int array[42];
char text[] = "Hello World";
int numbers = { 1, 2, 3, 4 };
(in the case of the latter two examples, the size is derived from the data)
You either need a newer compiler, to specify the -std=c99 if you are using GCC, or you need to allocate memory for the array yourself.
You're using a C89 (Visual Studio? Though that would give you an error on the declaration of arr next) or a C++ compiler. VLA's (Variable Length Arrays) are a C99 feature.
You need to allocate the memory in run-time . The compiler doesn't allow the declaration of arrays becuase it does not know the size of the array before hand . You need to use malloc() to allocate memory

(C) Function with bidimensional array

so I'm asked to make the following function:
int **multiplyM(int MA[][], int MB[][], int n, int m)
Which will multiply two matrices. The first one (MA) with dimensions n, n, and the second one (MB) with dimensions n, m. I have everything done with the program, but I get an error caused by the function itself, which says:
"array type has incomplete element type"
I know I can fix it by changing stuff in the function (like changing it to **MA and **MB), but the thing is, I'm not supposed to do that, because I'm supposed to make my program based on this function that was given to me.
So my question is: Is there a way to make this work WITHOUT changing the function?
The second dimension must be given for MA and MB
So,
#define SIZE_M 5 //Any constant
#define SIZE_N 6
int **multiplyM(int MA[][SIZE_M], int MB[][SIZE_N], int n, int m)
//Fix -> ^^^ ^^^
You cannot pass a multidimensional array to a function as you are doing. You need to specify the size of the the second dimension (and any further dimension) when declaring the function. Specifying the size here is important. If it were not mandatory, the compiler won't be able to deal with expression such Array[2][3]. The value used as array dimension must be a constant for ANSI C an other versions, but it can be a variable for C99 and successive versions. The C99 standard introduced the variable-length arrays feature, which allows to determine the size of an array at run-time.
So:
#define N 10
#define M 5
int **multiplyM(int MA[][N], int MB[][M], int n, int m)
I know I can fix it by changing stuff in the function (like changing
it to **MA and **MB), but the thing is, I'm not supposed to do that,
because I'm supposed to make my program based on this function that
was given to me.
Without modifying at least the declaration of the function, you are not going to solve this problem.

Simple error in C language

const int size = 10; // realna ilość danych
int tablica[size+1];
i have:
variable-size type declared outside of any function
Use
#define size 10
instead of a const int. The latter is not a compile-time constant in C, but a variable that cannot be assigned to (unless via a pointer and a cast to get rid of const).
(This is a difference between C and C++.)
You could use an enum.
enum
{
size = 10
};
int table[size + 1];
Use:
enum { size = 10 };
This is a constant value that can be used in declarations and in case labels and so on. In C99, inside a function, the original code would not be a problem -- your array tablica would be a VLA or variable-length array (and the compiler error message is trying to say "you can't have a VLA outside a function").
Using an enum gives better traceability when you use a debugger on your code; the symbol is included in the symbol table. Typically, C preprocessor symbols are not available to the debugger, so trying to print 'size' when it is #define'd doesn't print an answer; printing 'size' when it is an enum does.
See also: "static const" vs "#define" in C
The error is fairly self-explanatory. You can't declare a variable-length array outside of a function. Although the size of the array you're creating is, in practice, fixed at compile time, you've still technically violated the constraints of the language.
The usual choices are:
Move the array into a function. (Usually the best option, remember globals are to be avoided when possible.)
#define size n where n is the size you want, instead of using an int. (Usually better than "magic numbers", and pretty standard practice in traditional C.)
Use a "magic number" (int tablica[11];). (Usually the last choice, though sometimes it does make more sense.)

Resources