I am getting the error
"The expression needs to be a constant"
when I try to do this:
float mat1[m_Floats.size()][iNumClass];
Can I trick the compiler (VS2010) into compiling this anyway?
No. Only C99 specify dynamic array allocation (i.e. where size is known only at compile time). Maybe there is a MSVC extension to the standard, but you should go the canonical way in creating the array of pointers and each float subarray using new, like in:
float **mat1 = new float*[m_Floats.size()];
for (int i = 0; i < m_Floats.size(); ++i) {
mat1[i] = new float[iNumClass];
}
well, instead of "tricking the compiler", you can dynamically allocate your matrix with the operator new
No. The size of a declared array needs to be known at compile time. The value of m_Floats.size() depends on how many members are in that object.
If you need to allocate arrays with variable size, you'll need to handle it yourself with new or some appropriate classes/methods that encapsulate that for you.
Related
I understand that this question was asked before but I don't get why it doesn't work in my case
void calc(vector<char> zodis1, vector<char> zodis2, vector<char> zodisAts,int zo1,int zo2,int zoA)
{
int i,u=0;
int zod1[zo1]=0;
int zod2[zo2]=0;
int zodA[zoA]=0;
}
All 3 of zod1, zod2, zoA gives me error: variable-sized object may not be initialized c++
But compiler should know the meaning of zo before initialization cause cout<<zo1; works and print out the meaning
So whats the problem?
You can declare an array only with constant size, which can be deduced at compile time. zo1,zo2 and zoA are variables, and the values can be known only at runtime.
To elaborate, when you allocate memory on the stack, the size must be known at compile time. Since the arrays are local to the method, they will be placed on the stack. You can either use constant value, or allocate memory in the heap using new, and deallocate when done using delete, like
int* zod1 = new int[zo1];
//.... other code
delete[] zod1;
But you can use vector instead of array here also, and vector will take care of allocation on the heap.
As a side note, you should not pass vector by value, as the whole vector will be copied and passed as argument, and no change will be visible at the caller side. Use vector<char>& zodis1 instead.
Here is the fix, you can write the following lines instead of the line where you got the error;
Alternative 1 you can use vectors:
vector<int> zod1(zo1, 0);
Alternative 2 (for example, since w know "0 <= s.length <= 100", we can use constant value):
int zod1[100] = { 0 };
What is the difference between this two array definitions and which one is more correct and why?
#include <stdio.h>
#define SIZE 20
int main() {
// definition method 1:
int a[SIZE];
// end definition method 1.
// defintion method 2:
int n;
scanf("%d", &n);
int b[n];
// end definition method 2.
return 0;
}
I know if we read size, variable n, from stdin, it's more correct to define our (block of memory we'll be using) array as a pointer and use stdlib.h and array = malloc(n * sizeof(int)), rather than decalring it as int array[n], but again why?
It's not "more correct" or "less correct". It either is xor isn't correct. In particular, this works in C, but not in C++.
You are declaring dynamic arrays. Better way to declare Dynamic arrays as
int *arr; // int * type is just for simplicity
arr = malloc(n*sizeof(int*));
this is because variable length arrays are only allowed in C99 and you can't use this in c89/90.
In (pre-C99) C and C++, all types are statically sized. This means that arrays must be declared with a size that is both constant and known to the compiler.
Now, many C++ compilers offer dynamically sized arrays as a nonstandard extension, and C99 explicitly permits them. So int b[n] will most likely work if you try it. But in some cases, it will not, and the compiler is not wrong in those cases.
If you know SIZE at compile-time:
int ar[SIZE];
If you don't:
std::vector<int> ar;
I don't want to see malloc anywhere in your C++ code. However, you are fundamentally correct and for C that's just what you'd do:
int* ptr = malloc(sizeof(int) * SIZE);
/* ... */
free(ptr);
Variable-length arrays are a GCC extension that allow you to do:
int ar[n];
but I've had issues where VLAs were disabled but GCC didn't successfully detect that I was trying to use them. Chaos ensues. Just avoid it.
Q1 : First definition is the static array declaration. Perfectly correct.
It is when you have the size known, so no comparison with VLA or malloc().
Q2 : Which is better when taking size as an input from the user : VLA or malloc .
VLA : They are limited by the environment's bounds on the size of automatic
allocation. And automatic variables are usually allocated on the stack which is relatively
small.The limitation is platform specific.Also, this is in c99 and above only.Some ease of use while declaring multidimensional arrays is obtained by VLA.
Malloc : Allocates from the heap.So, for large size is definitely better.For, multidimensional arrays pointers are involved so a bit complex implementataion.
Check http://bytes.com/topic/c/answers/578354-vla-feature-c99-vs-malloc
I think that metod1 could be little bit faster, but both of them are correct in C.
In C++ first will work, but if you want to use a second you should use:
int size = 5;
int * array = new int[size];
and remember to delete it:
delete [] array;
I think it gives you more option to use while coding.
If you use malloc or other dynamic allocation to get a pointer. You will use like p+n..., but if you use array, you could use array[n]. Also, while define pointer, you need to free it; but array does not need to free.
And in C++, we could define user-defined class to do such things, and in STL, there is std::vector which do the array-things, and much more.
Both are correct. the declaration you use depends on your code.
The first declaration i.e. int a[size]; creates an array with a fixed size of 20 elements.
It is helpful when you know the exact size of the array that will be used in the code. for example, you are generating
table of a number n up till its 20th multiple.
The second declaration allows you to make an array of the size that you desire.
It is helpful when you will need an array of different sizes, each time the code is executed for example, you want to generate the fibonacci series till n. In that case, the size of the array must be n for each value of n. So say you have n = 5, in this case int a [20] will waste memory because only the first five slots will be used for the fibonacci series and the rest will be empty. Similarly if n = 25 then your array int a[20] will become too small.
The difference if you define array using malloc is that, you can pass the size of array dynamically i.e at run time. You input a value your program has during run time.
One more difference is that arrays created using malloc are allocated space on heap. So they are preserved across function calls unlike static arrays.
example-
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n;
int *a;
scanf("%d",&n);
a=(int *)malloc(n*sizeof(int));
return 0;
}
I'm trying to do a little application that would calculate some paths for a given graph.
I've created a class to handle simple graphs, as follows:
class SimpleGraph {
int _nbNodes;
int _nbLines;
protected:
int AdjMatrix[_nbNodes, _nbNodes]; //Error happens here...
int IncMatrix[_nbNodes, _nbLines]; //...and here!
public:
SimpleGraph(int nbNodes, int nbLines) { this->_nbNodes = nbNodes - 1; this->_nbLines = nbLines - 1; };
virtual bool isSimple();
};
At compilation time, I get an error on the two protected members declaration.
I don't understand what is wrong, as there is only one constructor that takes these values as parameters. As such, they cannot be uninitialized.
What am I missing here?
The compiler needs to know how much space to allocate for a member of class SimpleGraph. However, since AdjMatrix and IncMatrix are defined on the stack and their sizes are determined at run-time (i.e., after compilation), it cannot do that. Specifically, the standard says that the size of an array in a class must be a constexpr.
To fix this, you can:
Allocate AdjMatrix and IncMatrix on the heap instead and then you can allocate memory at runtime.
Use a fixed size for the two arrays and keep them on the stack.
--
Another major issue with your code is that you cannot create multi-dimensional arrays using a comma (AdjMatrix[int, int]). You must instead either use:
AdjMatrix[int][int]
AdjMatrix[int * int]
Objects in C++ have a fixed size that needs to be known at compilation time. The size of AdjMatrix and InMatrix are not known at compilation time, only at run time.
In the lines
int AdjMatrix[_nbNodes, _nbNodes]; //Error happens here...
int IncMatrix[_nbNodes, _nbLines]; //...and here!
The array notation is wrong. You cannot specify a 2 dimensional array that way in C++. The correct notation uses brackets on each dimension, as for instance:
int data[5][2];
Regarding the problem you are facing, the dimensions of an array in C++ must be specified at compile time, ie. the compiler must know what are the values used to indicate the array dimension when compiling the program. This is clearly not the case here. You must revert to use integer literals, as in my example, or change the code to use vectors:
std::vector<std::vector<int> > AdjMatrix;
and in the constructor:
SimpleGraph(int nbNodes, int nbLines) : AdjMatrix(nbNodes) {
for (int i = 0; i< nbNodes; i++)
AdjMatrix[i].resize(20);
}
Note that you won't need _nbNodes anymore, and use instead the size() method on AdjMatrix. You will have to do the same for IncMatrix.
Another option, if you know the values at compile time, is to use macros to define them symbolically.
#define NBNODES 20
int AdjMatrix[NBNODES][NBNODES];
but since you wish to pass them as constructor parameter, this may not fit your need. Still, if you know that the parameters are constants at compile time, you might be able use the C++11 constexpr qualifier on the constructor parameters.
What I'm trying to do right now is to create an array with a length that is defined by a variable. However, when I put the variable in the array length, it gives me a "Variable length array of non-POD element type 'glm::vec2'" error. However, if I replace the variable with an actual number, the error goes away. Why does this happen and how can I fix this?
int numtriangles = sector1.numtriangles;
glm::vec2 tex[test]; //Using a variable generates an error
glm::vec3 vertices[10]; //No error here
You cannot have variable length arrays(VLA) in standard C++.
Variable length arrays are not allowed by the C++ Standard. In C++ the length of the array needs to be a compile time constant. Some compilers do support VLA as a compiler extension, but using them makes your code non-portable across other compilers.
You can use, std::vector instead of an VLA.
See this question Is there a way to initialize an array with non-constant variables? (C++)
Short answer is no you cannot directly do this. However you can get the same effect with something like
int arraySize = 10;
int * myArray = new int[arraySize];
Now myArray is a pointer to the array and you can access it like an array like myArray[0], etc.
You can also use a vector which will allow you to have a variable length array. My example allows you to create an array with a variable initailizer however myArray will be only 10 items long in my example. If you aren't sure how long the array will ever be use a vector and you can push and pop items off it.
Also keep in mind with my example that since you've dyanmically allocated memory you will need to free that memory when you are done with the array by doing something like
delete[] myArray;
Here is a little sample app to illustrate the point
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int arraySize = 10;
int * myArray = new int[arraySize];
myArray[0] = 1;
cout << myArray[0] << endl;
delete[] myArray;
}
use STL.
IF you want a variable length array you can use vectors under #include<vector>
Native c++ array donot nave variable length array.
When you declare an array with a length specifier, only constants are allowed.
Actually it's when the program is compiled that the array length is evaluated.
Note however that it's illegal in C++ to declare int test[]; like the compiler has no way to know how much space to allocate for the variable.
Without a length specifier, there is no actual memory that is reserved for the array, and you have to resort to using pointers and dynamic memory allocation:
int * test = new int[12];
// or
int * test = new int[val]; // variable works here
// and don't forget to free it
delete [] test;
Using int test[12] actually creates an array that is statically initialized once and for all to contain 12 integers at compile time.
Do not ever attempt to do delete [] test with a variable declared this way, as it's most certainly going to make your program crash.
To be precise, if the array is declared in a function, it will use space on the program stack, and if declared in a global context, program data memory will be used.
C++ doesn't support declare variable length array. So to use a array with a length you may
Assume
a big number which is highest possible length of your array. Now declare an array of that size. And use it by assuming that it an array of your desire length.
#define MAX_LENGTH 1000000000
glm::vec2 tex[MAX_LENGTH];
to iterate it
for(i=0; i<test; i++) {
tex[i];
}
Note: memory use will not minimized in this method.
Use pointer and allocate it according your length.
glm::vec2 *tex;
tex = new glm::vec2[test];
enter code here
for(i=0; i<test; i++) {
tex[i];
}
delete [] tex; // deallocation
Note: deallocation of memory twice will occur a error.
Use other data structure which behave like array.
vector<glm::vec2> tex;
for(i=0; i<test; i++){
tex.push_back(input_item);
}
/* test.size() return the current length */
I am learning C++ and I just read about dynamic arrays and how it lets you set the length of an array during runtime rather than during compile time. However, you don't need a dynamic array to do this. So what is the point of a dynamic array; when would you use it? I feel like I am missing something obvious so any insight is much appreciated. Thanks!
// Static binding.
int size = 0;
cout << "Enter size of array:" << endl;
cin >> size;
int array[size];
int array_length = sizeof(array) / sizeof(int);
cout << "Number of elements in array: " << array_length << endl;
// I just set the length of an array dynamically without using a dynamic array.
// So whats the point of a dynamic array then?
I don't think you can do that in C++. Only C99 allows variable-length arrays.
Does this even compile? Were you talking about the vector class?
EDIT:
It does not compile in Visual Studio 2010:
1>..\main.c(207): error C2057: expected constant expression
1>..\main.c(207): error C2466: cannot allocate an array of constant size 0
1>..\main.c(207): error C2133: 'array' : unknown size
1>..\main.c(209): error C2070: 'int []': illegal sizeof operand
You would need a dynamically allocated array for cases where you don't know ahead of time how many items you will have.
Another (and better) option is to use std::vector.
As per the standard, an array defined "statically" would:
have a constant size, defined at compile time
Be allocated on the stack rather than the heap.
So the reasons you'd opt for a dynamically allocated array (using new type[]) are because you don't always know the size you need for an array at compile time, and the stack is a limited resource that you often need to be careful not to exhaust.
But in practical terms, you'd often be best served by using std::vector or other STL container instead of a builtin array of any sort.
Your example would not compile under a standards-compliant compiler. For instance, GCC says this:
http://codepad.org/Kvq2PfNx
In function 'int main()':
Line 13: error: ISO C++ forbids variable-size array 'array'
compilation terminated due to -Wfatal-errors.
There is a way of dynamically allocating stack memory using the alloca function. However, this memory is invalidated when the function terminates. You should generally prefer new[]/delete[] or std::vector for dynamic memory allocation.
You can dynamically create an array using the keyword new..
Lets say you don't know ahead of time how many values you need. It's a waste of space to declare an array a[100] when the user might just enter a few values. Also the user might enter more values, and then you would have a array overflow error.
You can create an array dynamically like - int a = new int[]
Also, statically created arrays are created on the stack where as dynamically created arrays are created on the heap-which means the memory is globally available even after the function goes out of scope.