Write a function, equalsArray that when passed two int arrays of the same length that is greater than 0 will return true if every number in the first array is equal to the number at the same index in the second array. If the length of the arrays is less than 1 the function must return false. For example, comparing the two arrays, {1,2,3,4,5} and {1,2,3,4,5} would return true but the two arrays {3,7} and {3,6} would return false.
You should start by copying the function-1-1.cpp file and name it function-3-1.cpp. Then add the function equalsArray to the new file.
The main function for this problem must call your readNumbers function twice, then pass both new arrays to your equalsArray function, display the result as true or false and finally delete the array. The main function in the file main-3-1.cpp.
The signature for your new function is:
bool equalsArray(int *numbers1,int *numbers2,int length) ;
This is my code, and i try to use the int* readNumber two times.
#include <iostream>
using namespace std;
int* readNumbers()
{
int* a = new int[10];
for (int i = 1; i < 11; i++) {
int x;
cin >> x;
a[i] = x;
}
a++;
return a;
// delete[] a;
}
bool equalsArray(int* numbers1, int* numbers2, int length)
{
if (length >= 1) {
for (int i = 0; i < length; i++) {
if (numbers1[i] == numbers2[i]) {
}
else {
return false;
}
}
return true;
}
// delete[] numbers1;
// delete[] numbers2;
int main()
{
int* arr1 = readNumbers();
int* arr2 = readNumbers();
equalsArray(arr1, arr2, 10);
return 0;
}
There there is an error,control reaches end of non-void function.
How to improve my code?
Thank you all.
Expect result:
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
7
8
9
10
True(1)
OK, first I will show you your code, with comments where the errors are.
Then I will show you a fixed version. And, at the end, a little bit more robust C++ soultion.
I know that you learn in school all this nasty stuff with pointers, decayed pointers for arrays, C-style arrays,pointers for owned memory, new and delete.
That is basically bad. It should never be used in C++.
Anyway. Teachers still think like that. What a pity . . .
OK. You code with comments:
#include <iostream>
using namespace std; // Should not be used
int* readNumbers()
{
int* a = new int[10]; // Do not use C-style arrays, pointer for owned memory, new and delete
for (int i = 1; i < 11; i++) { // Will lead to out of bound error
int x; // Why using additional variables?
cin >> x;
a[i] = x;
}
a++; // Wrong
return a;
// delete[] a; // Not here
}
bool equalsArray(int* numbers1, int* numbers2, int length)
{
if (length >= 1) {
for (int i = 0; i < length; i++) {
if (numbers1[i] == numbers2[i]) {
}
else {
return false;
}
}
return true;
}
// Here nothing will be returned
} // Closing bracket misding
// delete[] numbers1; // Not here
// delete[] numbers2; // Not here
int main()
{
int* arr1 = readNumbers();
int* arr2 = readNumbers();
equalsArray(arr1, arr2, 10);
return 0; // No output
} // No Release of memory
Next, your fixed code
#include <iostream>
using namespace std;
// Function to read a given numbers of values and returns them in a dynaimcally allocated array
int* readArrayOfNumbers(int numberOfValuesToRead) {
// Allocate a new array for the given amount of integers
int* dynamicArrayOfIntegers = new int[numberOfValuesToRead];
// Read all values in a loop from user via std::cin
for (int index = 0; index < numberOfValuesToRead; ++index) {
cin >> dynamicArrayOfIntegers[index];
}
return dynamicArrayOfIntegers;
}
// Compare 2 arrays with same size
bool equalsArray(int* numbers1, int* numbers2, int length) {
// We assume in the beginning that the arrays will be equal
bool result = true;
// We will only compare arrays, if they contain data
if (length >= 1) {
// Now compare arrays element by element
for (int i = 0; i < length; i++) {
if (numbers1[i] != numbers2[i]) {
// If not equal then set result to false and stop loop
result = false;
break;
}
}
}
else {
// No data in array. Consider as not equal
result = false;
}
return result;
}
int main()
{
// Define size of arrays
const int sizeOfArray = 10;
// Get 2 arrays in dynamically allocated arrays
int* array1 = readArrayOfNumbers(sizeOfArray);
int* array2 = readArrayOfNumbers(sizeOfArray);
// Compare both arrays
const bool arraysAreEqual = equalsArray(array1, array2, sizeOfArray);
// Show result
if (arraysAreEqual)
std::cout << "\nTrue(1)\n";
else
std::cout << "\nFalse(0)\n";
// Release memory
delete[] array1;
delete[] array2;
}
And finally, the C++ solution
#include <iostream>
#include <iomanip>
#include <array>
constexpr size_t NumberOfElements = 10u;
using MyType = int;
using MyArray = std::array<MyType, NumberOfElements>;
int main() {
// Define arrays
MyArray myArray1{};
MyArray myArray2{};
// Read values
for (size_t i{}; (i < NumberOfElements) and (std::cin >> myArray1[i]); ++i)
;
for (size_t i{}; (i < NumberOfElements) and (std::cin >> myArray2[i]); ++i)
;
// If all numbers could be read . . .
if (std::cin) {
// Show result of comparison
std::cout << '\n' << std::boolalpha << (myArray1 == myArray2) << '(' << (myArray1 == myArray2) * 1 << ")\n";
}
else std::cerr << "\n*** Error. Invalid input data\n";
}
Related
Write a function, reverseArray, that when passed an int array of length greater than 0 will return a dynamically allocated array of the same length but with the elements in the reverse order. For example, if passed the array, {1,2,3,4,5,6,7,8,9,0} the function would return the array {0,9,8,7,6,5,4,3,2,1}.
Below is my code, but there is a bug in it.
This is my output.
1
2
3
4
5
6
4113
6
5
4
3
2
1
0x7fffe697ceb0
The 4113 and address are provided by the compiler.
#include <iostream>
using namespace std;
int * readNumbers() {
int * a = new int[6];
for (int i = 0; i < 6; i++) {
int x;
cin >> x;
a[i] = x;
}
// a++;
return a;
delete[] a;
}
int *reverseArray(int *numbers1,int length) {
for (int i = length; i >=0; i--) {
cout << numbers1[i] << endl;
}
return numbers1;
delete [] numbers1;
}
int main() {
int *arr1 = readNumbers();
cout << reverseArray(arr1,6) << endl;
return 0;
}
I think there may have been an issue with your wording. Assuming you want your function just to print the reverse of a passed array, you're off to a good start.
One issue is what was said in the comments: your for loop is indexing past your array. When you type int * a = new int[6]; you are creating a pointer 'a' which points to a location in memory. Since you chose size 6, the appropriate amount of memory is allocated. If you happen to index outside of that range, you will end up pointing to a random spot in memory, not allocated for your array. Hence why you are getting a weird number '4113'.
A fix for this could be:
int i = length changed to int i = length-1
Another issue is that your function returns an integer pointer, and you are trying to cout this pointer. As another commenter said, you have to think about what this does. If you try this code:
#include <iostream>
using namespace std;
int main() {
int arr[] = {1, 2, 3};
cout << arr << endl;
return 0;
}
your output would be something like 0xff09ba. This represents the location of the start of the array in memory. If you change arr to (arr + 1) you will get the location of the second index of the array.
So when you type cout << reverseArray(arr1,6) << endl; you are really just printing out the location of numbers1 in memory. This is why you are getting '0x7fffe697ceb0' in your output. To fix this, simply make your function
void reverseArray(int *numbers1,int length) {
for (int i = length; i >=0; i--) {
cout << numbers1[i] << endl;
}
}
and change your main to:
int main() {
int *arr1 = readNumbers();
reverseArray(arr1,6);
return 0;
}
Now, if you actually want to return this array, you would need to create a new array which holds the reverse numbers and then return that. An example of a function that does that is:
int* reverseArray(int *numbers1,int length) {
int j = 0;
int *numbers2 = new int[length];
for (int i = length-1; i >=0; i--) {
numbers2[j] = numbers1[i];
j++;
}
return numbers2;
}
There are probably better ways to do this, but this is just one solution. Regardless, you should always be careful when allocating memory yourself.
I'm trying to delete all elements of an array that match a particular case.
for example..
if(ar[i]==0)
delete all elements which are 0 in the array
print out the number of elements of the remaining array after deletion
what i tried:
if (ar[i]==0)
{
x++;
}
b=N-x;
cout<<b<<endl;
this works only if i want to delete a single element every time and i can't figure out how to delete in my required case.
Im assuming that i need to traverse the array and select All instances of the element found and delete All instances of occurrences.
Instead of incrementing the 'x' variable only once for one occurence, is it possible to increment it a certain number of times for a certain number of occurrences?
edit(someone requested that i paste all of my code):
int N;
cin>>N;
int ar[N];
int i=0;
while (i<N) {
cin>>ar[i];
i++;
}//array was created and we looped through the array, inputting each element.
int a=0;
int b=N;
cout<<b; //this is for the first case (no element is deleted)
int x=0;
i=0; //now we need to subtract every other element from the array from this selected element.
while (i<N) {
if (a>ar[i]) { //we selected the smallest element.
a=ar[i];
}
i=0;
while (i<N) {
ar[i]=ar[i]-a;
i++;
//this is applied to every single element.
}
if (ar[i]==0) //in this particular case, we need to delete the ith element. fix this step.
{
x++;
}
b=N-x;
cout<<b<<endl;
i++;
}
return 0; }
the entire question is found here:
Cut-the-sticks
You could use the std::remove function.
I was going to write out an example to go with the link, but the example form the link is pretty much verbatim what I was going to post, so here's the example from the link:
// remove algorithm example
#include <iostream> // std::cout
#include <algorithm> // std::remove
int main () {
int myints[] = {10,20,30,30,20,10,10,20}; // 10 20 30 30 20 10 10 20
// bounds of range:
int* pbegin = myints; // ^
int* pend = myints+sizeof(myints)/sizeof(int); // ^ ^
pend = std::remove (pbegin, pend, 20); // 10 30 30 10 10 ? ? ?
// ^ ^
std::cout << "range contains:";
for (int* p=pbegin; p!=pend; ++p)
std::cout << ' ' << *p;
std::cout << '\n';
return 0;
}
Strictly speaking, the posted example code could be optimized to not need the pointers (especially if you're using any standard container types like a std::vector), and there's also the std::remove_if function which allows for additional parameters to be passed for more complex predicate logic.
To that however, you made mention of the Cut the sticks challenge, which I don't believe you actually need to make use of any remove functions (beyond normal container/array remove functionality). Instead, you could use something like the following code to 'cut' and 'remove' according to the conditions set in the challenge (i.e. cut X from stick, then remove if < 0 and print how many cuts made on each pass):
#include <iostream>
#include <vector>
int main () {
// this is just here to push some numbers on the vector (non-C++11)
int arr[] = {10,20,30,30,20,10,10,20}; // 8 entries
int arsz = sizeof(arr) / sizeof(int);
std::vector<int> vals;
for (int i = 0; i < arsz; ++i) { vals.push_back(arr[i]); }
std::vector<int>::iterator beg = vals.begin();
unsigned int cut_len = 2;
unsigned int cut = 0;
std::cout << cut_len << std::endl;
while (vals.size() > 0) {
cut = 0;
beg = vals.begin();
while (beg != vals.end()) {
*beg -= cut_len;
if (*beg <= 0) {
vals.erase(beg--);
++cut;
}
++beg;
}
std::cout << cut << std::endl;
}
return 0;
}
Hope that can help.
If you have no space bound try something like that,
lets array is A and number is number.
create a new array B
traverse full A and add element A[i] to B[j] only if A[i] != number
assign B to A
Now A have no number element and valid size is j.
Check this:
#define N 5
int main()
{
int ar[N] = {0,1,2,1,0};
int tar[N];
int keyEle = 0;
int newN = 0;
for(int i=0;i<N;i++){
if (ar[i] != keyEle) {
tar[newN] = ar[i];
newN++;
}
}
cout<<"Elements after deleteing key element 0: ";
for(int i=0;i<newN;i++){
ar[i] = tar[i];
cout << ar[i]<<"\t" ;
}
}
Unless there is a need to use ordinary int arrays, I'd suggest using either a std::vector or std::array, then using std::remove_if. See similar.
untested example (with c++11 lambda):
#include <algorithm>
#include <vector>
// ...
std::vector<int> arr;
// populate array somehow
arr.erase(
std::remove_if(arr.begin(), arr.end()
,[](int x){ return (x == 0); } )
, arr.end());
Solution to Cut the sticks problem:
#include <climits>
#include <iostream>
#include <vector>
using namespace std;
// Cuts the sticks by size of stick with minimum length.
void cut(vector<int> &arr) {
// Calculate length of smallest stick.
int min_length = INT_MAX;
for (size_t i = 0; i < arr.size(); i++)
{
if (min_length > arr[i])
min_length = arr[i];
}
// source_i: Index of stick in existing vector.
// target_i: Index of same stick in new vector.
size_t target_i = 0;
for (size_t source_i = 0; source_i < arr.size(); source_i++)
{
arr[source_i] -= min_length;
if (arr[source_i] > 0)
arr[target_i++] = arr[source_i];
}
// Remove superfluous elements from the vector.
arr.resize(target_i);
}
int main() {
// Read the input.
int n;
cin >> n;
vector<int> arr(n);
for (int arr_i = 0; arr_i < n; arr_i++) {
cin >> arr[arr_i];
}
// Loop until vector is non-empty.
do {
cout << arr.size() << endl;
cut(arr);
} while (!arr.empty());
return 0;
}
With a single loop:
if(condition)
{
for(loop through array)
{
if(array[i] == 0)
{
array[i] = array[i+1]; // Check if array[i+1] is not 0
print (array[i]);
}
else
{
print (array[i]);
}
}
}
This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 8 years ago.
I'm at college and we're learning pointers. Our job was to input a char, compare it to an array and return a pointer to the first reference of that char in the array. But, as I don't like easy things, I've asked my teacher what about having that char more than once in the array.
That's where my headache begins.
So I have this code. The idea is: create a function that compares the input char to the entire array, get the pointers of the references and save them in an array and return that array.
Unfortunately it's not working as I wish :(
What can be wrong?
#include<iostream>
#include<cstdlib>
using namespace std;
char list [10];
int main()
{
initialize();
show();
cout<<search('1');
}
void initialize()
{
int i;
for(i=0; i<10;i++)
{
list[i]='1';
}
}
void show()
{
int i;
for(i=0; i<10;i++)
{
cout<<list[i];
}
}
int* search(char* input)
{
int* result[10];
int i;
char *temp;
for (i=0; i<10; i++)
{
*temp=list[i];
if(strcmp(temp, input) != NULL)
{
result[i]=i;
}
}
return result[];
}
I'm on a mobile device so I can't go into huge detail unfortunately, but you are returning a pointer to an array that you create in the function which goes out of scope at the end of the function.
My massive edit:
As everyone has already stated, a C++ array is actually only a pointer to the first element in the array. As a result, if you return a pointer to an array created in the scope of the function, you are returning a pointer to garbage. If I were doing this I would use a vector, but if I were to be forced into using an array, I would use something like the code below. Hope this helps!
#include <iostream>
#include <cstdlib>
void initialize(char* list) {
for(int i = 0; i < 10; ++i) {
if(i < 4) {
list[i] = '2';
} else {
list[i] = '1';
}
}
}
void show(char *list) {
for(int i = 0; i < 10; ++i) {
std::cout << list[i] << ' ';
}
std::cout << std::endl;
}
// Note the function requires an additional argument that is a pointer
// this is how you can avoid returning a pointer
int search(char input, char* list, char* result) {
int j = 0;
for(int i = 0; i < 10; ++i) {
// comparing characters can be done via ==
if(input == list[i]) {
*(result + j) = list[i];
// You could use result[j], but I used this to show that
// result really is just a pointer to the first element
// of the array. As a result saying result[j] is the same
// as saying I want to deference j elements past the first
// element or *(result + j)
++j; // increment j
}
}
// return how many elements matched
return(j);
}
int main(int argc, char *argv[]) {
char list[10];
char temp[10];
initialize(list);
show(list);
int size = search('1', list, temp);
// create a dynamically sized array containing space for each match
// because we don't know the size at compile time we must use
// a library type or a dynamically sized array
char *result = new char[size];
for(int i = 0; i < size; ++i) {
result[i] = temp[i];
// again you could use result[i]
std::cout << *(result + i) << std::endl;
}
delete[] result; // otherwise you'll get a memory leak
return(0);
}
I have two multidimensional arrays
uint8_t arr1 [24][8];
uint8_t arr2 [24][8];
I am writing a function to print out the contents of these arrays, and I wish to specify to the function which of the arrays I want printed. I tried the following:
void print_array(int n) {
uint8_t arr[24][8];
if (n == 1) {
arr = arr1;
}
else if (n == 2) {
arr = arr2;
}
// ... code to print "arr" contents ...
}
Basically, I want to be able to copy the reference to the multidimensional array to avoid having duplicated code to print the array contents. The above gives me an 'invalid array assignment' error. What do I need to do to copy the array reference successfully?
When an array is used as a value (I'm talking of C arrays) then its name represents the address of the first element. This means that either you need to copy the memory by hand somehow (memcpy) or that you need to use that pointer somehow.
For the second choice (recommended since there's no copy involved) this will work:
#include <iostream>
using namespace std;
uint8_t arr1 [24][8];
uint8_t arr2 [24][8];
void print_array(int n) {
uint8_t (*arr)[24][8];
if (n == 1) {
arr = &arr1;
}
else if (n == 2) {
arr = &arr2;
}
for(int i=0; i<24; i++){
for(int j=0; j<8; j++)
printf("\n %d ", (int)(*arr)[i][j]);
}
}
int main() {
arr1[0][1] = 3;
arr1[1][5] = 6;
print_array(1);
return 0;
}
Try it live: http://ideone.com/CvMQfB
Also notice that if you're using C++11, then you might get away with std::array and have exactly what you had in mind with the same syntax
std::array<int,4> A = {10,20,30,40};
std::array<int,4> B = A; //copy array A into array B
You could create pointer to array:
void print_array(int n) {
uint8_t (*arr)[24][8];
if (n == 1) {
arr = &arr1;
}
else if (n == 2) {
arr = &arr2;
}
// ... code to print "arr" contents ...
}
I would do something like :
void print_array(const uint8_t (&arr)[24][8]) {
for (std::size_t i = 0; i != 24; ++i) {
for (std::size_t j = 0; j != 8; ++j) {
std::cout << arr[i][j] << " ";
}
std::cout << std::endl;
}
}
then call it print_array(arr1); or print_array(n == 1 ? arr1 : arr2);.
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
}