Variable length in a Simple Matrix c++ [duplicate] - c++

This question already has answers here:
Why can't I create an array of size n? [duplicate]
(5 answers)
Why aren't variable-length arrays part of the C++ standard?
(10 answers)
Closed 9 months ago.
I'm using VS 2019. In this code:
using namespace std;
int main()
{
cout << "Inserisci la dimensione della matrice:";
int DIM;
DIM = 2;
cin >> DIM;
int v[DIM][DIM];
return 0;
}
I Don't understand why in:
int v[DIM][DIM];
I've this error:
The expression must have a constant value. It is not possible to use the "DIM" variable value as a constant.

In C++, the size of an array must be a compile time constant. So you cannot write code like:
int n = 10;
int arr[n]; //incorrect
Correct way to write this would be:
const int n = 10;
int arr[n]; //correct
So we cannot use the input given by the user as the size of the array. That is why you are getting the mentioned error.
You can use std::vector in place of built in array to solve your problem.

some compiler/c++ version doesn't support variable length arrays compile time. we can create dynamic array on heap. Below code works for you
using namespace std;
int main()
{
cout << "Inserisci la dimensione della matrice:";
int DIM;
DIM = 2;
cin >> DIM;
int **v = new int*[DIM];
for (int i=0;i<DIM;i++)
v[i] = new int[DIM];
// now you can use it as 2D array i.e
v[0][0] = 12;
cout<<v[0][0];
return 0;
}

Related

What's wrong with the space for an array declaration in c++? [duplicate]

This question already has answers here:
C/C++ the result of the uninitialized array
(2 answers)
Uninitialized variable behaviour in C++
(4 answers)
What happens when I print an uninitialized variable in C++? [duplicate]
(4 answers)
(Why) is using an uninitialized variable undefined behavior?
(7 answers)
Closed 4 months ago.
I have long been declaring a lot more space for arrays during competitive programming.
int pr[100010]; //for example
However, when I was trying to declare an array for a smaller space this morning, things went wrong.
#include <iostream>
using namespace std;
int main()
{
int n; cin >> n;
int pr[100]; //seems enough
for(int i = 1; i <= n; i++) {
int x; cin >> x;
pr[i] = pr[i-1] + x;
}
for(int i = 1; i <= n; i++)
cout << pr[i] << endl;
return 0;
}
You see, this program was for calculating the prefix sum of an array. The value for this array comes from input.
The space for this array seems enough.
But when I input these to my program and found that it occurs to a wrong output:
//the input:
5
1 2 3 4 5
//the output:
1875947561
1875947563
1875947566
1875947570
1875947575
The array might just out of bounds. I thought.
However, when I modified the space 100 to 10, the answer was correct this time!
#include <iostream>
using namespace std;
int main()
{
int n; cin >> n;
int pr[10]; //smaller, but correct!
for(int i = 1; i <= n; i++) {
int x; cin >> x;
pr[i] = pr[i-1] + x;
cout << "*" << pr[i] << endl;
}
for(int i = 1; i <= n; i++)
cout << pr[i] << endl;
return 0;
}
5
1 2 3 4 5
1
3
6
10
15
It seems that the problem happend at here:
pr[i] = pr[i-1] + x;
I know that the initial value of the array was 0, but why a smaller space works well and the higher space didn't ?
The most interesting thing is that when I declare the array as a global variable, though small, the answer was correct?
#include <iostream>
using namespace std;
int pr[1]; //such a tiny space but correct!
int main()
{
int n; cin >> n;
for(int i = 1; i <= n; i++) {
int x; cin >> x;
pr[i] = pr[i-1] + x;
}
for(int i = 1; i <= n; i++)
cout << pr[i] << endl;
return 0;
}
The results:
//the input
5
1 2 3 4 5
//the output
1
3
6
10
15
This problem confuses me a whole day, can someone help me? I can't fell asleep as the problem was still there :(
The problem is here:
int pr[100]; //seems enough
for(int i = 1; i <= n; i++) {
int x; cin >> x;
pr[i] = pr[i-1] + x; // uninitialized read of pr[0]
}
Reading an uninitialized variable is undefined behavior. In this case you read some garbage value, but your program could also crash or produce other unexpected results.
As a side note, your program does not need an array at all. You could output each value as soon as you calculate it, and store the current sum in a scalar.
Conclusion
If you declare a global variable, it would be initialized to zero.
For a local variable, you have to initialize it before use.
For that global pr[1], it can work, but with error.

Exponential values not taking in large array [duplicate]

This question already has answers here:
The program doesn't give any output on VS Code if I use 'const int ' and assign it a big value like 1e6 [duplicate]
(1 answer)
Why is this C++ program crashing? [duplicate]
(2 answers)
C++ program is not giving output involving large array
(5 answers)
Closed 9 months ago.
Whenever is give N = 1e6 + 2 like large value to N. VS Code doesn't work and on runtime shows .exe stopped working. Couldn't figure out why happening
#include <iostream>
using namespace std;
int main()
{
int n, arr[n];
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
int N = 1e6 + 2;
bool check[N];
for (int i = 0; i < N; i++)
{
check[i] = false;
}
return 0;
}

Array as an argument of a function in C++ [duplicate]

This question already has answers here:
How does sizeof know the size of array? [duplicate]
(7 answers)
Using sizeof on arrays passed as parameters [duplicate]
(3 answers)
Closed 2 years ago.
This is a question on C++. I tried defining a function that computes the average of all elements in an array of doubles as follows, through the sizeof function that enables us to compute the length of the array.
#include<iostream>
#include<cstddef>
using namespace std;
double getAverage(double arr[]) {
double sum =0;
double avg;
size_t size = sizeof(arr)/sizeof(*arr); \\ to calculate the length of the array arr
for (size_t i = 0; i < size; ++i) {
sum += arr[i];
}
avg = sum / size;
return avg;
}
int main () {
double balance[] = {1000, 2, 3, 17, 50};
double avg = getAverage(balance) ;
cout << "Average value is: " << avg << endl;
return 0;
}
However, instead of 214.4, it returns 1000, which is clearly wrong. Is it legitimate to pass an array as an argument of a function in C++?

Usage of sizeof(array)/sizeof(array[0]) within function c++ [duplicate]

This question already has answers here:
When passing an array to a function in C++, why won't sizeof() work the same as in the main function?
(1 answer)
Difference between passing array and array pointer into function in C
(3 answers)
Closed 3 years ago.
I have a question concerning the sizeof(array)/sizeof(array[0]), especially when you use it within a function. I wanted to get the size of the array (number of elements in that array) through that expression, however it gives me unexpected behavior. When I enter 5 for n, within the function calculateSum I cannot receive the array length of 5 when I use sizeof(a)/sizeof(a[0]).
I am still a beginner in C++, can you give some explanation to this kind of behavior? Why is it safer to pass the length of the array as a parameter?
Here is a sample input:
5 (length)
1 2 3 4 5 (input for a)
4 5 3 2 10 (input for b)
The lengths of a, b, and c are the same.
Thank you very much.
#include<iostream>
using namespace std;
int * calculateSum(int a[], int b[]){
int* c = new int[sizeof(a)/sizeof(a[0])];
for(int i = 0;i < sizeof(a)/sizeof(a[0]);i++){
c[i] = a[i]+b[i];
}
return c;
};
int main(){
int n = 0;
cin>>n;
int a[n];
int b[n];
// enter everything for array a first and elements of array b
for(int i=0;i<n;i++){
cin>>a[i];
}
for(int i=0;i<n;i++){
cin>>b[i];
}
int *c;
c=calculateSum(a,b);
for(int i=0;i<n;i++){
cout<<*(c+i)<<" ";
}
delete[] c;
return 0;
}

Printing array in C++ error [duplicate]

This question already has answers here:
Returning a reference to a local variable in C++
(3 answers)
Closed 8 years ago.
Trying to make a program that sums 5 digit numbers by each digit. For some reason when I attempt to print individual elements of an array (one element at a time running 5 times) I get the correct value of 69134. But when I print them together:
int *addArray(int arr1[], int arr2[]){
int arrSum[5];
int r=0;
for(int i=4; i>=0; i--){
arrSum[i]=(arr1[i]+arr2[i]+r)%10;
r=((arr1[i]+arr2[i]+r)>=10);
}
return arrSum;
}
int main(){
using namespace std;
int data1[5]={1,2,3,4,5};
int data2[5]={5,6,7,8,9};
int *arrSum=addArray(data1,data2);
cout << arrSum[0] << arrSum[1] << arrSum[2] << arrSum[3] << arrSum[4];
return 0;
}
I end up with the result 60000. Anyone know what is going on?
In addArray you are returning a pointer to a local variable (arrSum), which results in undefined behaviour. You should either pass in the result array from the calling function, or allocate the array dynamically. For example, using the first approach:
void addArray(const int arr1[], const int arr2[], int arrSum[])
{
int r=0;
for(int i=4; i>=0; i--)
{
arrSum[i]=(arr1[i]+arr2[i]+r)%10;
r=((arr1[i]+arr2[i]+r)>=10);
}
}
int main()
{
int data1[5]={1,2,3,4,5};
int data2[5]={5,6,7,8,9};
int arrSum[5];
addArray(data1,data2,arrSum);
cout << arrSum[0] << arrSum[1] << arrSum[2] << arrSum[3] << arrSum[4];
return 0;
}