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 << ",";
}
}
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]<<", ";
}
}
I'm having trouble understanding how to pass a dynamic array by reference in C++.
I've recreated the problem in this small isolated code sample:
#include <iostream>
using namespace std;
void defineArray(int*);
int main()
{
int * myArray;
defineArray(myArray);
/** CAUSES SEG FAULT*/
//cout<<(*(myArray)); //desired output is 0
return 0;
}
void defineArray(int*myArray)
{
int sizeOfArray;
cout<<"How big do you want your array:";
cin>>sizeOfArray;
/** Dynamically allocate array with user-specified size*/
myArray=new int [sizeOfArray];
/** Define Values for our array*/
for(int i = 0; i < sizeOfArray; i++)
{
(*(myArray+i))=i;
cout<<(*(myArray+i));
}
}
myArray is passed by value itself, any modification on myArray (such as myArray=new int [sizeOfArray];) has nothing to do with the original variable, myArray in main() is still dangled.
To make it passed by reference, change
void defineArray(int*myArray)
to
void defineArray(int*& myArray)
This solution is hopelessly complicated. You don't need new[], pointers or even a reference parameter. In C++, the concept of "dynamic arrays" is best represented by std::vector, which you can just just use as a return value:
#include <iostream>
#include <vector>
std::vector<int> defineArray();
int main()
{
auto myArray = defineArray();
if (!myArray.empty())
{
std::cout << myArray[0] << "\n";;
}
}
std::vector<int> defineArray()
{
int sizeOfArray;
std::cout << "How big do you want your array:";
std::cin >> sizeOfArray;
std::vector<int> myArray;
for (int i = 0; i < sizeOfArray; i++)
{
myArray.push_back(i);
std::cout<< myArray[i] << "\n";
}
return myArray;
}
push_back will work intelligently enough and not allocate new memory all the time. If this still concerns you, then you can call reserve before adding the elements.
Please refer to the code (and comments) below. I am trying to make array = newArray. What is the correct syntax to do this in C++? I am trying to point array to the same memory location as newArray in memoryCopy(), thus copying newArray into array, without having to do it element-by-element as I did in deepCopy()
#include <iostream>
using namespace std;
void deepCopy(int array[], int size);
void memoryCopy(int *array, int size);
void show(int array[], int size);
int main ()
{
int array[] = {1,1,1};
show(array,3); // shows array [] = {1,1,1}
deepCopy(array, 3);
show(array,3); // shows array [] = {0,0,0}
memoryCopy(array, 3);
show(array,3); // shows array [] = {5,0,0}
// I need the above to show {5, 5, 5} ^ ^
// How can I do this in memoryCopy() using pointers?
}
void memoryCopy(int *array, int size)
{
int newArray[] = {5,5,5};
// I need to make array = newArray ...
// ... but without copying it over element by element
memcpy(array,newArray, 3); // <--???
}
void deepCopy(int array[], int size)
{
int newArray [] = {0,0,0};
for (int i = 0; i < size; i++)
array[i] = newArray[i];
}
void show(int array[], int size)
{
int i;
cout << "array [] = {";
for (i = 0; i < size-1; i++)
cout << array[i] << ",";
cout << array[i] << "}" << endl;
}
If C++ 11 or newer is available, use std::array<T,N> instead of C-Style array.
Example:
std::array<int,3> my_array {1,1,1};
auto new_array=my_array; // deep copy
Thank you all for the quick responses!
SO much help so fast, you are awesome!
Below is how it worked
void shallowCopy(int *array, int size)
{
int newArray[] = {5,5,5};
memcpy(array,newArray, 3*sizeof(int)); // <--WORKS
// thank you Manthan Tilva!
}
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];
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]<<", ";
}
}