so this is what i'm suppose to do but its got me kinda confused, this is what i got so far any help would be appreciated:)
Write a function that dynamically allocates an array of integers. The function should accept an integer argument indicating the number of elements to allocate and should return a pointer to the array. Then write a driver in the main function that generates a random number (something not too large), calls the function, and verifies access by saving a value to the first element and displaying the contents of that element.
edited code it runs but i feel like im not using my function at all.
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;
int *MyArray(int);
int main()
{
srand(time(0));
int random = rand() % 5 + 1;
const int size = 5;
int array[size];
MyArray(size);
array[0] = random;
cout << array[0] << endl;
}
int *MyArray(int numOfElements)
{
int *array;
array = new int[numOfElements];
return array;
}
edited code
int main()
{
srand(time(0));
int random = rand() % 5 + 1;
const int size = 5;
int* array = MyArray(size);
array[0] = random;
cout << array[0] << endl;
delete [] array;
}
I believe you try to do something like this:
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;
int *MyArray(int);
int main()
{
srand(time(0));
int random = rand() % 5 + 1;
int *array = MyArray(random); //! store the pointer of dynamically allocated memory and use it.
array[0] = random;
cout << array[0] << endl;
delete [] array; //! To avoid memory leak
}
int *MyArray(int numOfElements)
{
int *array = new int[numOfElements];
return array;
}
Note: I'm just guessing this is what you probably looking for.
Related
I'm learning C++ and I'm wondering if anyone can explain some strange behaviour I'm seeing.
I'm currently learning memory management and have been playing around with the following code:
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
// pass back by pointer (old C++)
const int array_size = 1e6; // determines size of the random number array
vector<int> *RandomNumbers1()
{
vector<int> *random_numbers = new vector<int>[array_size]; // allocate memory on the heap...
for (int i = 0; i < array_size; i++)
{
int b = rand();
(*random_numbers).push_back(b); // ...and fill it with random numbers
}
return random_numbers; // return pointer to heap memory
}
int main (){
vector<int> *random_numbers = RandomNumbers1();
for (int i = 0; i < (*random_numbers).size(); i++){
cout << (*random_numbers)[i] + "\n";
}
delete random_numbers;
}
What I'm trying to do is get a pointer to a vector containing random integers by calling the RandomNumbers1() function, and then print each random number on a new line.
However, when I run the above code, instead of printing out a random number, I get all sorts of random information. It seems as though the code is accessing random places in memory and printing out the contents.
Now I know that I'm doing something stupid here - I have an int and I am adding the string "\n" to it. If I change the code in main() to the following, it works fine:
int main (){
vector<int> *random_numbers = RandomNumbers1();
for (int i = 0; i < (*random_numbers).size(); i++){
cout << to_string((*random_numbers)[i]) + "\n";
}
}
However I just can't understand the behaviour I'm getting with the "wrong" code - i.e. how adding the string "\n" to (*random_numbers)[i]
causes the program to access random areas of memory, instead of where my pointer is pointing to. Surely I have de-referenced the pointer and accessed the element at position i before "adding" "\n" to it? So how is the program instead accessing a totally different memory address?
"\n" is a string literal. It is an array and it is converted to a pointer pointing at its first element in your expression.
(*random_numbers)[i] is an integer.
Adding a pointer to an integer means that advance the pointer by the integer.
This will drive the pointer to out-of-range because "\n" has only 2 elements ('\n' and '\0') but the numbers returnd from the rand() function are likely to be larger than 2.
There are several issues with your code.
you are using delete instead of delete[] to free the array allocated with new[].
you are creating an array of 1000000 vectors, but populating only the 1st vector with 1000000 integers. You probably meant to create just 1 vector instead.
you can and should use the -> operator when accessing an object's members via a pointer. Using the * and . operators will also work, but is more verbose and harder to read/code for.
you are trying to print a "\n" after each number, but you are using the + operator when you should be using the << operator instead. You can't append a string literal to an integer (well, you can, but it will invoke pointer arithmetic and thus the result will not be what you want, as you have seen).
With that said, try something more like this:
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
const int array_size = 1e6; // determines size of the random number array
vector<int>* RandomNumbers1()
{
vector<int> *random_numbers = new vector<int>;
random_numbers->reserve(array_size);
for (int i = 0; i < array_size; ++i)
{
int b = rand();
random_numbers->push_back(b);
}
return random_numbers;
}
int main (){
vector<int> *random_numbers = RandomNumbers1();
for (size_t i = 0; i < random_numbers->size(); ++i){
cout << (*random_numbers)[i] << "\n";
}
/* alternatively:
for (int number : *random_numbers){
cout << number << "\n";
}
*/
delete[] random_numbers;
}
However, if you are going to return a pointer to dynamic memory, you really should wrap it inside a smart pointer like std::unique_ptr or std::shared_ptr, and let it deal with the delete for you:
#include <iostream>
#include <vector>
#include <cmath>
#include <memory>
using namespace std;
const int array_size = 1e6; // determines size of the random number array
unique_ptr<vector<int>> RandomNumbers1()
{
auto random_numbers = make_unique<vector<int>>();
// or: unique_ptr<vector<int>> random_numbers(new vector<int>);
random_numbers->reserve(array_size);
for (int i = 0; i < array_size; ++i)
{
int b = rand();
random_numbers->push_back(b);
}
return random_numbers;
}
int main (){
auto random_numbers = RandomNumbers1();
for (size_t i = 0; i < random_numbers->size(); ++i){
cout << (*random_numbers)[i] << "\n";
}
/* alternatively:
for (int number : *random_numbers){
cout << number << "\n";
}
*/
}
Though, in this case, there is really no good reason to create the vector dynamically at all. 99% of the time, it is unnecessary and unwanted to use standard containers like that. Since the vector manages dynamic memory internally, there is no reason for the vector itself to also be created in dynamic memory. Return the vector by value instead, and let the compiler optimize the return for you.
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
const int array_size = 1e6; // determines size of the random number array
vector<int> RandomNumbers1()
{
vector<int> random_numbers;
random_numbers.reserve(array_size);
for (int i = 0; i < array_size; ++i)
{
int b = rand();
random_numbers.push_back(b);
}
return random_numbers;
}
int main (){
vector<int> random_numbers = RandomNumbers1();
for (size_t i = 0; i < random_numbers.size(); ++i){
cout << random_numbers[i] << "\n";
}
/* alternatively:
for (int number : random_numbers){
cout << number << "\n";
}
*/
}
I'm learning pointers in but I'm stuck on dynamic allocation of arrays.
The code below provides a function to find the element with the lowest value.
A dynamically allocated array is passed as a parameter to it.
#include <cstdlib>
#include <iostream>
using namespace std;
int findMin(int *arr, int n);
int main()
{
int *nums = new int[5];
int nums_size = sizeof(*nums);
cout << "Enter 5 numbers to find the minor:" << endl;
for(int i = 0; i < nums_size; i++)
cin >> nums[i];
cout << "The minor number is " << findMin(*nums, nums_size);
delete [] nums;
return 0;
}
But it return this error:
error: invalid conversion from ‘int’ to ‘int*’ [-fpermissive]
How can I pass that array to the function?
Just for curiosity: why the for loop allows me to enter 4 value if my array is made up of 5 elements?
How can I pass that array to the function?
nums is already a type int*, you don't need to dereference it:
findMin(nums, nums_size);
why the for loop allows me to enter 4 value if my array is made up of 5 elements?
int nums_size = sizeof(*nums); does not do what you think it does. It's equivalent to sizeof(nums[0]), which is equivalent to sizeof(int), which happens to be equal to 4 at your machine.
There is no way to extract size of array allocated on the heap, you need to save the size on your own:
int nums_size = 5;
int* nums = new int[nums_size];
#include <cstdlib>
#include <iostream>
using namespace std;
int findMin(int *arr, int n){
int mn=INT_MAX;
for(int i=0;i<n;i++){
if(arr[i]<mn){
mn=arr[i];
}
}
return mn;
};
int main()
{
int nums_size = 5;
int *nums = new int[nums_size];
cout << "Enter 5 numbers to find the minor:" << endl;
for(int i = 0; i < nums_size; i++)
cin >> nums[i];
cout << "The minor number is " << findMin(nums, nums_size);
delete [] nums;
return 0;
}
The above code works fine. Your error was in passing the array to the function.
Also to add -
Your code made only 4 iterations coz sizeof(*nums) returned the size of base index element pointed by pointer, i.e ,sizeof(num[0]). So I made a minor change and now it works fine.
I am studying for an exam I have next week and am having troubles understanding Dynamic memory allocation. I have a question given which I dont know how to answer;
line 4: int *arr = new int[3];
Write a function that includes the line 4 above and returns the size of the memory location occupied by variable arr. Use the signature:
int size_of_variable_star_arr() ;
I assume I should be using both a main.cpp and a function.cpp - the main file should contain the array variables, while the function file should contain the array that returns it.
Not entire sure what to do here though in order to return the size of the memory location.
//Main.cpp
#include <iostream>
using namespace std;
int main(){
//int *arr = new int[3];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
cout << "Array: ";
}
//function.cpp
#include <iostream>
using namespace std;
int size_of_variable_star_arr(){
int *arr = new int[3];
for(int i = 0; i < 4; i++){
cout << arr[i] << " ";
}
return 0;
}
This is a really strange question, but here's the answer anyway:
int size_of_variable_star_arr() {
int *arr = new int[3];
delete [] arr;
return sizeof(arr);
}
Notes:
I added delete [] to undo the (unnecessary) new
It returns the size of variable arr, as stated in the question. Not the size of the memory block which arr points to.
I get an error when I try to call my member function to copy the array into another array. Im not sure if I am calling it wrong or what. I think I have the syntax right on most parts but I am also not sure if it matter if the member function is a void or int.
Main.cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "Class.h"
using namespace std;
int main()
{
// Max size of array
int MaxRange = 1000;
// Get System time
unsigned seed = time(0);
// seed random number generator
srand(seed);
// allocate memory for array
int * Array = new int[1000];
int * CopiedArray = new int[1000];
// Randomly generate numbers into array
for (int i = 0; i < 1000; i++)
{
Array[i] = 1 + rand() % MaxRange;
}
//print array
for (int j = 0; j < 1000; j++)
{
cout << Array[j] << endl;
}
CopiedArray = Sort.CopyArray(Array);
return 0;
}
Class.h
#include <iostream>
using namespace std;
class Sort
{
public:
void CopyArray(int * Array);
};
Class.cpp
#include <iostream>
#include "Class.h"
using namespace std;
void CopyArray::CopyArray(int * Array)
{
// Allocate memory for copied array
int * CopiedArray = new int[1000]
//copy date to array
for(int i = 0; i < 1000; i++)
{
CopiedArray[i] = Array[i]
}
cout << " THIS IS THE COPIED ARRAY" << endl;
// print copied array
for (int j = 0; i < 1000; i++)
{
cout << CopiedArray[j] << endl;
}
}
in your example you are accessing a member function CopyArray without an object you cannot do that. you must create an object of class Sort then use it to access the members. otherwise make CopyArray static and then change it to
class Sort
{
public:
static int* CopyArray(int* Array); // to access this function just use the name of class and `::`
// int* CopyArray(int* Array); // to access this function you must have an object of Sort class
};
int* Sort::CopyArray(int * Array)
{
int * CopiedArray = new int[1000]; // semicolon missin
// your code processing here
return CopiedArray;
}
int main()
{
CopiedArray = Sort::CopyArray(Array); // accessing the static member function `CopyArray`
// or you can create an object of Sort class but you must also make Copyarray non-static to be able to:
// Sort theSort;
// CopiedArray = theSort.CopyArray(Array);
return 0;
}
* also in your example you are assigning a void to a pointer to int:
CopiedArray = Sort.CopyArray(Array);// because in your example CopyArray returns void.
CopiedArray = Sort.CopyArray(Array);
however this function is defined as void
void CopyArray::CopyArray(int * Array)
You can not set a pointer to the result of a void function.
And of course you did not declare in instance of Sort and CopyArray is not staic like #Bim mentioned.
You should also not change the value of CopiedArray because it was allocated and you need to free it.
Sorry your code is really a mess.
im doing simple genetic algorithm uniform crossover operation . for that im using two arrays as parent and mother.i want concatenate the childs for getting the offsprings(childs).
i have problem in adding the arrays .any help plssss.i did it ubuntu
#include<iostream>
#include <fstream>
#include <algorithm>
#include<vector>
using namespace std;
int main()
{
int P[ ]={3,7,6,5,2,4,1,8};
int N[ ]={8,6,7,2,5,3,4,1};
int r= (sizeof(P)/sizeof(*P)) ;
int s= (sizeof(N)/sizeof(*N));
int val=r/2 ;
int t1[val],t2[val],t3[val],t4[val],n=0,p=0;
for(int m=0;m< val;m++)
{
t1[n]=P[m];
t2[n]=N[m];
n++;
}
for(int x=val;x< r;x++)
{
t3[p]=P[x];
t4[p]=N[x];
n++;
}
int* child=new int [val+val];
copy(t1,t1+val,child);
copy(t3,t3+val,child+val);
cout << child;
}
return 0;
}
This part is wrong:
int t1[val], t2[val], t3[val], t4[val]
You can only use constant values to declare the size of arrays.
You can either use a std::vector or dynamically allocate memory for the t-arrays.
std::vector<int> t1(val);
std::vector<int> t2(val);
for(int m = 0; m < val; m++)
{
t1[n] = P[m];
t2[n] = N[m];
n++;
}
There seem to be multiple errors in your code.
Variable length arrays are at present not supported in C++.
int val=r/2 ;
int t1[val]; // Not OK
In the second for loop I guess you meant p++ instead of n++;
Instead of manually doing all the memory allocation - deallocation, you should use std::vectors
cout << child; // This outputs the address of the pointer, not the entire array.