When I try to run this simple code, it returns a Variable-sized object may not be initialized error. I have no idea why and how to resolve this problem.
int main()
{
int n=0;
n=1;
int a[n]={}, b[n]={};
return 0;
}
The array lenght must be known at compile time.
Either
int a[1];
or
constexpr int n = 1;
int a[n];
Otherwise you need a dynamic array like the std container std::vector.
You can initialize your array properly with the std::fill_n like:
std::fill_n(a, n, 0);
std::fill_n(b, n, 0);
or use std::vector like:
std::vector<int> a(n);
It will initialize all the elements to 0 by default.
Or, you can have something like:
constexpr size_t n = 10;
int a[n]{};
This will also initialize all the elements to 0.
Try this:
const int n=1;
int main()
{
int a[n]={}, b[n]={};
return 0;
}
The above code will let you create an array with length n.
Note: n can't be changed.
Related
I would like to create a struct which contains both an int and an array of int. So I define it like
struct my_struct {
int N ;
int arr[30] ;
int arr[30][30] ;
}
Then I would like to initialize it with an array which I have already defined and initialized, for example
int my_arr[30] ;
for (int i = 0; i < 30; ++i)
{
my_arr[i] = i ;
}
Then I thought I could initialize a struct as
my_struct A = {30,my_arr}
but it doesn't seem to work (gives conversion error).
P.s. and how would it work with a 2d array?
Arrays cannot be copy-initialised. This isn't particular to the array being member of a class; same can be reproduced like this:
int a[30] = {};
int b[30] = a; // ill-formed
You can initialise array elements like this:
my_struct A = {30, {my_arr[0], my_arr[1], my_arr[2], //...
But that's not always very convenient. Alternatively, you can assign the array values using a loop like you did initially. You don't have to write the loop either, there's a standard algorithm for this called std::copy.
#include <iostream>
#include <array>
using namespace std;
int main(){
int a = [];
int b = 10;
std::fill(a);
cout<<a<<endl;
}
I have an array "a" and want to fill it with an integer "b". As I remember in python its simply uses apppend, does someone know solution?
Here one solution how to use your array header.
int b = 10;
std::array<int, 3> a;
std::fill(begin(a), end(a), b);
I have an array "a"
int a = [];
What you have is a syntax error.
As I remember in python its simply uses apppend
A major difference between a C++ array and python list is that the size of C++ array cannot change, and thus nothing can be appended into it.
How to fill array in C++?
There is indeed a standard algorithm for this purpose:
int a[4];
int b = 10;
std::fill_n(a, std::size(a), b);
Decide the size for a, as it is an array not a list. For example:
int a[10];
Then use index values to fill in the array like:
a[0] = 1;
a[1] = 4;
etc.
If you want a dynamic array use std::vector instead
Here is how its done with vectors:
std::vector<int> myvector;
int myint = 3;
myvector.push_back (myint);
Following zohaib's answer:
If your array is of fixed length:
You can use the array's 'fill' member function like this:
a.fill(b);
If your array can change it's size you can use the std's fill function like this:
std::fill(a.begin(), a.end(), b);
How to create a 2d array using dynamic memory allocation in c++?
Maze(int c=10){
const int m=c;
a=new int[m][m];
}
void main(){
Maze(12);
}
std::vector is the typical way to have a dynamically allocated array in C++. You can have a vector of vectors to make it two-dimensional. Here's an example:
std::vector<std::vector<int>> a(m,std::vector<int>(m));
If you want it inside a class:
struct Maze {
std::vector<std::vector<int>> a;
Maze(int m) : a(m,std::vector<int>(m)) { }
};
Easily - using multiplication. Also I suggest using reference to array because in this way you specify the type more explicitly then using a pointer to it's first element. I'm actually amazed why this isn't the type most programmers use. Perhaps because they're lazy and the type is complex ;).
void Maze(int c=10) {
const int m=c;
int (&a)[0][0] = *(int (*)[0][0])new int[/*numbers of rows*/ m * sizeof(int) * m /* number of colums on each row*/];
}
Here 'a' is an reference to the newly created array. As types aren't dynamic in 'C++' language we assume that it has zero elements on each of it's dimensions. But of-course we can access more then 0.
Now if you have a function with parameter of type 2 dim array it will look like this:
void func(int (&_2dimarray)[0][0]) ;
Or if you want to return it from your 'Maze' you could write:
int (&Maze(int c=10))[0][0] {
const int m=c;
int (&a)[0][0] = *(int (*)[0][0])new int[/*numbers of rows*/ m * sizeof(int) * m /* number of colums on each row*/];
return a;
}
Life example.
But of-course the easiest way is using 'std::vector' which however can have performance cost on some compilers while the built-in array will more surely run fast everywhere.
EDIT: The explanation is simple - the 'new []' can be thought as a function like:
template<class T>
T *operator new T[] (std::size_t);
Your instance of it:
a=new int[m][m];
Can also look like this (illustrative)
a=operator new int[m][](m);
Which fulfills 'T' with 'int[m]'.
This is illegal because 'int[m]' is not valid type. 'C++' supports only static types and this is not such because the length of the array can't be determined during compile-time as 'm' is not a constant. The last 'm' is a function parameter to 'operator new[]'.
Yep I also think this construct isn't the most elegant yet but this is the life.
There are two approaches. If the size of the internal one-dimensional subarray is a constant value known at compile time then you can write
const size_t N = 10;
int ( * )[N] Maze( size_t n = N )
{
return new int[n][N];
}
int main()
{
int ( *a )[N] = Maze( 12 );
//...
delete [] a;
}
If it is not a constant then you need to allocate a one-dimensional array of pointers to one-dimensional arrays. For example
const size_t N = 10;
int ** Maze( size_t n = N )
{
int **p = new int *[n];
for ( size_t i = 0; i < n; i++ ) p[i] = new int[n];
return p;
}
int main()
{
int **a = Maze( 12 );
//...
for ( size_t i = 0; i < 12; i++ ) delete [] a[i];
delete [] a;
}
Also you could use smart pointers as for example std::unique_ptr.
The other approach is to use standard container std::vector<std::vector<int>>
I am trying to solve a dynamic programming problem and I need to take the user input in the form of a 2-d array and use the values from the 2-d array inside the function.
The values of the 2-d array will not be changed when used inside the function.
In the function int dp i am getting the
error:
declaration of 'a' as multidimensional array must have bounds for all dimensions except the first
int max(int a,int b,int c)
{
if(a>=b && a>=c)return a;
if(b>=c && b>=a)return b;
else return c;
}
int max2(int a,int b)
{
if(a>b)return a;
else return b;
}
int dp(int i,int j,int a[][],int p,int q)
{
if((i-1)>=0 && (j-1)>=0 &&(i+1)<p &&(j+1)<q )
return max(a[i][j]+dp(i-1,j+1,a,p,q),a[i][j]+dp(i+1,j+1,p,q),
a[i][j]+dp(i,j+1,p,q));
if(i==0 && j!=0 && (j+1)<q)
return max2(a[i][j]+dp(i+1,j+1,p,q),a[i][j]+dp(i,j+1,p,q));
}
int main()
{
int p,q,r,s,T,a,b,i,j,k;
scanf("%d",&T);
for(a=0;a<T;a++)
{
scanf("%d %d",p,q);
int z[p][q];
int max=0;
for(i=0;i<q;i++)
{
for(j=0;j<p-1;j++)
scanf("%d ",&z[j][i]);
scanf("%d",&z[j+1][i]);
}
for(i=0;i<p;i++)
{
if(dp(i,0,z,p,q)>max)
max=dp(i,0,z,p,q);
}
}
}
It's all in the error message:
declaration of 'a' as multidimensional array must have bounds for all dimensions except the first
Your function signature does not have bounds for a's 2nd dimension:
int dp(int i,int j,int a[][],int p,int q)
// ^^^^^
You need to fill it in with a[][N] where N is whatever the correct bound is. The issue is that you are using VLAs here:
scanf("%d %d",p,q);
int z[p][q];
That is non-standard C++, and basically means you cannot write the signature of dp, since the second bound has to be known as a compile-time constant. You could either make it a single-dimensional array:
int* z = new int[p*q];
int dp(int i, int j, int* a, int p, int q)
// ^^^^^^
or dynamically allocate it in 2 dimensions and just pass it in that way:
int** z = new int*[p];
for (int i = 0; i < p; ++i) {
z[i] = new int[q];
}
int dp(int i, int j, int** a, int p, int q)
// ^^^^^^^
The function dp needs some information to perform meaningful index calculations, either done by the compiler or in the actual inplementation. Either a dimension must be specified in the type or the argument a could be of type int** while its dimensions are provided as separate arguments to dp. As this is C++, a type of std::vector< std::vector< int > > might be more suitable for the task.
You get that error because you cannot leave both the index(row,column) empty in int a[][] in your function declaration. You must have both specified or atleast the value of column index.
Use dynamic declaration
int **z = new int*[p];
for (int i = 0; i < p; i++)
z[i] = new int[q];
Change the parameter int a[][] to int **a
You can't dynamically declare an array on the stack as the size has to be known at compile time. The only way to do this would be by allocating memory for the array on the heap using the new keyword, then you could declare the size at run time.
Far easier, however, would be just to use a container class, or in your case, a container of containers like a vector of vector of ints;
#include <vector>
vector< vector<int> > arrArray(rows, vector<int>(columns));
The syntax might look a bit strange, but breaking it down;
vector<int> - a vector of type int
vector< vector<int> > - a vector of vectors of type int
arrArray(rows, vector<int>(columns)); - here in the first parameter, we are saying; create rows number of vector<int>'s in our array, and the second parameter initalises the array to some value. If it were just a 2D array of int, we might initalise it to 0, or omit the second parameter and rely on the default value of int. But, because our multidimensional vector also contains vectors, we set each row of our main vector to store a vector of int's which holds columns amount of integers.
Now you can access the array like you would any other;
arrArray[2][0] = 5;
You also get all the added benefits that container classes contain, including iterators and a lot of useful class methods for manipulating and checking your array. Once you understand the syntax of creating container classes, you'll find them much easier to work with than arrays. You also don't have to worry about having to manage your own memory, and have the ability to do bounds checking before accessing vector elements.
I'm trying to return a pointer to an array from a function but I have an issue. When I try to output like this:
#include <iostream>
using namespace std;
int* Somma_Array(int[],int[],int);
int main()
{
int n;
cin>>n;
int A[n],B[n];
for(int i=0;i<n;i++)cin>>A[i];
for(int i=0;i<n;i++)cin>>B[i];
int *c=Somma_Array(A,B,n);
for(int i=0;i<n*2;i++)cout<<c[i];
}
int* Somma_Array(int v[],int p[],int size)
{
int r[size*2];
for(int i=0;i<size;i++)r[i]=v[i];
for(int i=0;i<size;i++)r[i+size]=p[i];
return r;
}
it prints weird numbers instead of the actual number. I tried to do what this question says but it does not work. It gives me the following warning:
[Warning] address of local variable 'r' returned [enabled by default]
I'm using bloodshed dev-c++.
You define a stack allocated array r, which is destroyed when you exit the function Soma_Array. This is one of the (many) reasons vectors are preferred to plain arrays - they handle allocation and deallocation for you.
#include <vector>
std::vector<int> getArray()
{
std::vector<int> a = {1, 2, 3};
return a;
}
The following:
int r[size*2];
defines r locally. When the function exits (as in the scope of the function expires), r will be destroyed since it is bound to the function's scope. You are likely seeing junk data from the stack frame.
you could fix this by doing the following:
int* r = new int[size * 2];
The variable r will now be heap allocated and exist beyond the scope of the function.
IMPORTANT by doing this, you now must manually free r when you are done with it. So for instance, your calling code will look something like this:
int* result = Somma_Array(v, p, size);
/* ... do stuff ... */
delete[] result;
Since r is an array, note the use of delete[] instead of delete. delete[] is the correct way to destroy arrays.
A Better Alternative
Would std::vector be more what you are after? This is a much safer alternative to hand-rolled arrays. The vector is safer to use, scales automatically as you add elements, and cleans itself up nicely when it leaves scope (assuming you are using a value-type instance). Additionally, vectors can be copied and moved out of functions easily.
You cannot return arrays in C++. Especially, you should not return a pointer to a local array. You can however return a std::vector<int>:
std::vector<int> Somma_Array(int v[], int p[], int size)
{
std::vector<int> r(2 * size);
std::copy(v, v + size, r.begin());
std::copy(p, p + size, r.begin() + size);
return r;
}