I get an error under "int dArray[size]" saying that size needs to be a constant. Can someone explain what that means exactly?
I want it to be an array of size 4 and output 1, 3, 5, and 7.
#include <iostream>
using namespace std;
int *AllocateArray(int size, int value){
int dArray[size];
for (int i = 0; i <= size; i++){
dArray[i] = value;
value + 2;
}
}
int main(){
AllocateArray(4, 1);
}
Solved:
Here is the code that ended up working.
#include <iostream>
using namespace std;
int *AllocateArray(int size, int value){
int * Array = new int[size];
for (int i = 0; i < size; i++){
Array[i] = value;
value = value + 2;
}
for (int i = 0; i < size; i++){
cout << Array[i] << endl;
}
return Array;
}
int main(){
int *dArray = AllocateArray(4, 1);
}
In int dArray[size] size is not a constant value. Because of that you are getting that error. What you probably wanted to do was make a new array using a pointer and new like:
int * dArray = new int[size];
C++ requires that the size of arrays are determined at compile-time. As size is determined at runtime, the compiler complains.
If you are interested in having array-like behaviour with a size unknown at compile-time, then consider using std::vector.
The size of array should be a known constant in compile time, so that compiler can allocate correct memory for that array on the stack. Remember that such a declare is for stack variable. If you do want dynamic array, try std::vector.
You have to declare the size of an array using numbers, #define or const unsigned int. Otherwise they are considered variable length arrays.
Example:
const unsigned int MAX_ARRAY_SIZE = 14;
double my_array[MAX_ARRAY_SIZE];
Related
Is there a way to take two int arrays in C++
int * arr1;
int * arr2;
//pretend that in the lines below, we fill these two arrays with different
//int values
and then combine them into one larger array that contains both arrays' values?
Use std::copy defined in the header <algorithm>. The args are a pointer to the first element of the input, a pointer to one past the last element of the input, and a pointer to the first element of the output.
( https://en.cppreference.com/w/cpp/algorithm/copy )
int * result = new int[size1 + size2];
std::copy(arr1, arr1 + size1, result);
std::copy(arr2, arr2 + size2, result + size1);
Just suggestion, vector will do better as a dynamic array rather than pointer
If you're using arrays, you need to allocate a new array large enough to store all of the values, then copy the values into the arrays. This would require knowing the array sizes, etc.
If you use std::vector instead of arrays (which has other benefits), this becomes simpler:
std::vector<int> results;
results.reserve(arr1.size() + arr2.size());
results.insert(results.end(), arr1.begin(), arr1.end());
results.insert(results.end(), arr2.begin(), arr2.end());
Another alternative is to use expression templates and pretend the two are concatenated (lazy evaluation). Some links (you can do additional googling):
http://www10.informatik.uni-erlangen.de/~pflaum/pflaum/ProSeminar/
http://www.altdevblogaday.com/2012/01/23/abusing-c-with-expression-templates/
http://aszt.inf.elte.hu/~gsd/halado_cpp/ch06s06.html
If you are looking for ease of use, try:
#include <iostream>
#include <string>
int main()
{
int arr1[] = {1, 2, 3};
int arr2[] = {3, 4, 6};
std::basic_string<int> s1(arr1, 3);
std::basic_string<int> s2(arr2, 3);
std::basic_string<int> concat(s1 + s2);
for (std::basic_string<int>::const_iterator i(concat.begin());
i != concat.end();
++i)
{
std::cout << *i << " ";
}
std::cout << std::endl;
return 0;
}
Here is the solution for the same-
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
void Concatenate(char *s1,char *s2)
{
char s[200];
int len1=strlen(s1);
int len2=strlen(s2);
int j;
///Define k to store the values on Kth address Kstart from 0 to len1+len2;
int k=0;
for(j=0;j<len1;j++)
{
s[k]=s1[j];
k++;
}
for(j=0;j<len2;j++)
{
s[k]=s2[j];
k++;
}
///To place a null at the last of the concatenated string to prevent Printing Garbage value;
s[k]='\n';
cout<<s;
}
int main()
{
char s1[100];
char s2[100];
cin.getline(s1,100);
cin.getline(s2,100);
Concatenate(s1,s2);
return 0;
}
Hope it helps.
for (int i = 0; i< arraySize * 2; i++)
{
if (i < aSize)
{
*(array3 + i) = *(array1 + i);
}
else if (i >= arraySize)
{
*(array3 + i) = *(array2 + (i - arraySize));
}
}
This might help you along, it doesn't require vectors. I had a similar problem in my programming class. I hope this helps, it was required that I used pointer arithmetic. This assumes that array1 and array2 are initialized dynamically to the size "aSize"
Given int * arr1 and int * arr2, this program Concatenates in int * arr3 the elements of the both arrays. Unfortunately, in C++ you need to know the sizes of each arrays you want to copy. But this is no impediment to choose how many elements you want to copy from arr1 and how many from arr2.
#include <iostream>
using namespace std;
int main(){
int temp[] = {1,2,3,4};
int temp2[] = {33,55,22};
int * arr1, * arr2, *arr3;
int size1(4), size2(3); //size1 and size2 is how many elements you
//want to copy from the first and second array. In our case all.
//arr1 = new int[size1]; // optional
//arr2 = new int[size2];
arr1=temp;
arr2=temp2;
arr3 = new int;
//or if you know the size: arr3 = new int[size1+size2];
for(int i=0; i<size1+size2; i++){
if (i<size1)
arr3[i]=arr1[i];
else
arr3[i] = arr2[i-size1];
}
cout<<endl;
for (int i=0; i<size1+size2; i++) {
cout<<arr3[i]<<", ";
}
}
class Solution {
public:
int numSquares(int n) {
int dp[n+1];
for(int i=0;i<=n;i++) dp[i]=0; //initializing all the elements to zero
for(int i=1;i<=n;i++){
int t = INT_MAX;
for(int j=1;j<=(int)sqrt(i);j++){
t = min(t,dp[i-j*j]);
}
dp[i] = t+1;
}
return dp[n];
}
};
The above method works perfectly fine but when I tried to initialize the array like this
int dp[n] = {0} //variable sized array cannot be initialized
I am getting error like variable sized array cannot be initialized .
Is there any why to initialize this array instead of using for loop and please explain me why I am getting this error?.
The problem is that in C++, the size of an array must be a compile time constant. So,
int n = 10;
int arr[n] ; //incorrect
The correct way would be:
const int n = 10;
int arr[n]; //correct
You can solve your problem by using:
const int n = 10;
int arr[n] = {0}; //correct now because n is a constant expression
Some more examples:
void func(int n)
{
int arr[n] = {0}; //incorrect because n is passed as a function argument and is therefore not a compile time constant
}
Another example
int n;
cin >> n;
int arr[n] = {0}; //incorrect
You can use std::vector as it is a dynamic sized container.
what are all the different ways to initialize a c++ array?
They are:
default initialisation (which means "no initialisation" in case of trivial objects)
list initialisation
value initialisation (which is list initialisation with an empty list)
why I am getting this error?.
Your program is ill-formed. The size of an array variable must be compile time constant, but n+1 is not.
You are using a language extension. As the error message implies, the language extension doesn't allow all forms of initialisation to be used. You can use default initialisation i.e. "no" initialisation as you did in the first code example.
but what if you are getting the array size as a parameter in a function in class?
Then create a dynamic array. I recommend using std::vector.
what are all the different ways to initialize a c++ array?
That's described here: Aggregate initialization.
The main problem is that VLA:s (variable length arrays) do not exist in standard C++ so instead of int dp[n+1]; you should use std::vector<int> dp(n+1);
Example:
#include <algorithm>
#include <climits>
#include <cmath>
#include <vector>
class Solution {
public:
int numSquares(int n) {
std::vector<int> dp(n + 1); // instead of `int dp[n+1];`
// for(int i=0;i<=n;i++) dp[i]=0; // no need
for(int i = 1; i <= n; i++) {
int t = INT_MAX;
for(int j = 1, end = (int) std::sqrt(i); j <= end; ++j) {
t = std::min(t, dp[i - j * j]);
}
dp[i] = t + 1;
}
return dp[n];
}
};
I am trying to create a program that will take an original array, create one that is twice as large, and then have the original values appear twice.
I am pretty sure my code for the function is correct, but I cannot figure out what I need to put in main to make it work. I am currently getting "Expected '(' for function-style cast or type construction" and "Cannot refer to class template 'array' without a template argument list" compiler errors.
Any ideas on what I need to fix to make this work?
void repeatArray(double **array, int size)
{ //Dynamically allocate array that holds an amount of elements = size
double *resize = new double[size * 2];
for (int i = 0; i < size; i++)
{
resize[i] = (i + 1) * 2;
delete [] *array;
*array = resize;
}
}
int main()
{
const int size = 5;
**array[] = {1.1, 2.2, 3.3, 4.4};
repeatArray(double **array, size);
for (int i; i < size; i++)
{
cout << array;
}
}
You are trying to allocate a one dimensional array and make a pointer pointer point to the data that is allocated for a one dimensional array, also you are calling the wrong delete on memory allocated for a one dimensional array.
If the goal is to double the size of an array that you have allocated dynamically using new, then you can do the following
void resizeArray(int** arr, int new_size) {
delete[] (*arr);
*arr = new int[new_size];
// do your initialization here
}
int main() {
const int size = 5;
int* arr = new int[5];
resizeArray(&int, 5);
}
Although keep in mind that when you are working with dynamic arrays. It is almost always better to use std::vector than to roll your own arrays.
In C++14
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
template<typename T>
void repeatArray(std::vector<T> &array) {
int element_count = array.size();
array.resize(2*element_count);
for (int i=0; i<element_count; i++)
array[i+element_count] = array[i];
}
int main() {
vector<float> array = {1.1, 2.2, 3.3, 4.4};
repeatArray(array);
for (auto &i : array) {
cout << i << ",";
}
}
Is there a way to take two int arrays in C++
int * arr1;
int * arr2;
//pretend that in the lines below, we fill these two arrays with different
//int values
and then combine them into one larger array that contains both arrays' values?
Use std::copy defined in the header <algorithm>. The args are a pointer to the first element of the input, a pointer to one past the last element of the input, and a pointer to the first element of the output.
( https://en.cppreference.com/w/cpp/algorithm/copy )
int * result = new int[size1 + size2];
std::copy(arr1, arr1 + size1, result);
std::copy(arr2, arr2 + size2, result + size1);
Just suggestion, vector will do better as a dynamic array rather than pointer
If you're using arrays, you need to allocate a new array large enough to store all of the values, then copy the values into the arrays. This would require knowing the array sizes, etc.
If you use std::vector instead of arrays (which has other benefits), this becomes simpler:
std::vector<int> results;
results.reserve(arr1.size() + arr2.size());
results.insert(results.end(), arr1.begin(), arr1.end());
results.insert(results.end(), arr2.begin(), arr2.end());
Another alternative is to use expression templates and pretend the two are concatenated (lazy evaluation). Some links (you can do additional googling):
http://www10.informatik.uni-erlangen.de/~pflaum/pflaum/ProSeminar/
http://www.altdevblogaday.com/2012/01/23/abusing-c-with-expression-templates/
http://aszt.inf.elte.hu/~gsd/halado_cpp/ch06s06.html
If you are looking for ease of use, try:
#include <iostream>
#include <string>
int main()
{
int arr1[] = {1, 2, 3};
int arr2[] = {3, 4, 6};
std::basic_string<int> s1(arr1, 3);
std::basic_string<int> s2(arr2, 3);
std::basic_string<int> concat(s1 + s2);
for (std::basic_string<int>::const_iterator i(concat.begin());
i != concat.end();
++i)
{
std::cout << *i << " ";
}
std::cout << std::endl;
return 0;
}
Here is the solution for the same-
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
void Concatenate(char *s1,char *s2)
{
char s[200];
int len1=strlen(s1);
int len2=strlen(s2);
int j;
///Define k to store the values on Kth address Kstart from 0 to len1+len2;
int k=0;
for(j=0;j<len1;j++)
{
s[k]=s1[j];
k++;
}
for(j=0;j<len2;j++)
{
s[k]=s2[j];
k++;
}
///To place a null at the last of the concatenated string to prevent Printing Garbage value;
s[k]='\n';
cout<<s;
}
int main()
{
char s1[100];
char s2[100];
cin.getline(s1,100);
cin.getline(s2,100);
Concatenate(s1,s2);
return 0;
}
Hope it helps.
for (int i = 0; i< arraySize * 2; i++)
{
if (i < aSize)
{
*(array3 + i) = *(array1 + i);
}
else if (i >= arraySize)
{
*(array3 + i) = *(array2 + (i - arraySize));
}
}
This might help you along, it doesn't require vectors. I had a similar problem in my programming class. I hope this helps, it was required that I used pointer arithmetic. This assumes that array1 and array2 are initialized dynamically to the size "aSize"
Given int * arr1 and int * arr2, this program Concatenates in int * arr3 the elements of the both arrays. Unfortunately, in C++ you need to know the sizes of each arrays you want to copy. But this is no impediment to choose how many elements you want to copy from arr1 and how many from arr2.
#include <iostream>
using namespace std;
int main(){
int temp[] = {1,2,3,4};
int temp2[] = {33,55,22};
int * arr1, * arr2, *arr3;
int size1(4), size2(3); //size1 and size2 is how many elements you
//want to copy from the first and second array. In our case all.
//arr1 = new int[size1]; // optional
//arr2 = new int[size2];
arr1=temp;
arr2=temp2;
arr3 = new int;
//or if you know the size: arr3 = new int[size1+size2];
for(int i=0; i<size1+size2; i++){
if (i<size1)
arr3[i]=arr1[i];
else
arr3[i] = arr2[i-size1];
}
cout<<endl;
for (int i=0; i<size1+size2; i++) {
cout<<arr3[i]<<", ";
}
}
I am getting a crash error at run time and not sure what exactly to do with the function or how to get the data for it.
FUNCTION DETAILS
Write a function that accepts an int array and size as arguments, then create a new array that is one element bigger than the given. Setting the first element to 0, then copying over what is in the argument array to the new array.
MAIN DETAILS
Use in a program reading int n from input, then read int n from file data name data
passing it to element shifter, then printing it to output (one per line).
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int element_shift(int elmts[], int size) {
int new_size = size + 1;
int shifter[new_size];
int *elmt_sft;
shifter[0] = 0;
for (int i = 1; i >= new_size; i++) {
shifter[i + 1] = elmts[i];
}
return *elmt_sft;
}
int main() {
fstream infile;
infile.open("D:\\data.txt");
int n, x;
infile >> x;
cout << "size of array: ";
cin >> n;
const int ARRAY_SIZE = n + x;
int elements[ARRAY_SIZE];
element_shift(elements, ARRAY_SIZE);
system("PAUSE");
return EXIT_SUCCESS;
}
First of all ARRAY_SIZE declared in the main function is not a constant variable but defined at run-time depending on user inputs. This means that the array elements should be created dynamically. On the other hand you read some x variable which is only used to define the size of the array and didn't initialized the array at all. I guess that the problem statement is to read the size of the array from the input, then the data of the array from the file.
There are also lot of mistakes in element_shift function.
Your code should look like something similar to this:
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
void element_shift(int* elmts, int size)
{
int new_size = size + 1;
int* shifter = new int[new_size];
shifter[0] = 0;
for(int i = 0; i < size; ++i)
{
shifter[i + 1] = elmts[i];
}
delete [] elmts;
elmts = shifter;
}
int main()
{
fstream infile;
infile.open("D:\\data.txt");
int n;
cout << "size of array: ";
cin >> n;
int* elements = new int[n];
for (int i = 0; i < n; ++i) {
infile >> elements[i];
}
element_shift(elements, n);
for (int i = 0; i < n; ++i) {
std::cout << elements[i] << std::endl;
}
return EXIT_SUCCESS;
}
First off, you spend alot of time creating the shifted array but don't return it back.
int element_shift(int elmts[], int size) {
int new_size = size + 1;
int shifter[new_size];
int *elmt_sft;
shifter[0] = 0;
for (int i = 1; i >= new_size; i++) {
shifter[i + 1] = elmts[i];
}
return *elmt_sft;
}
The elmt_sft pointer is never assigned. You are trying to access memory that is not there by using *elmt_sft. This may be causing your error. Also this function has no way of returning the new array shifter because that variable is locally declared and will disappear once the function exits. If you want to create something new in the function and still have it in memory once the function exits, I recommend creating the array dynamically and returning a pointer to it.
This is untested but should start you in the right direction. It will return a separate dynamically allocated array that will not override your other one.
int* element_shift(int elmts[], int size) {
int *result_array = new int[size + 1]; //dynamically create new array MAKE SURE TO DELETE
result_array[0] = 0; //set 0 index to 0
for (int i = 1; i < size + 1; i++)//start at 1 of the result and put value in
{
result_array[i] = elmts[i - 1];
}
return result_array; //returning pointer
}