C++ filling in array with input from another - c++

I'm just taking input for two arrays and manipulating the information. When I take input for both arrays it puts the information from the second into both arrays. In the code below I haven even commented out the input for the second array to see what happens and it still puts the input for M into both arrays. Can anyone see the cause?
int M[0], N[0];
std::cin >> m >> n;
for (int i = 0; i < m; ++i)
{
std::cin >> M[i];
}
for(int i=0; i<m; i++)
{
std::cout << M[i];
}
std::cout << "\n";
for(int i=0; i<n; i++)
{
std::cout << N[i];
}

For starters these declarations
int M[0], N[0];
are invalid, You may not declare an array with zero elements.
Thus the code has undefined behavior.
Secondly variable length arrays are not a standard C++ feature. Either declare the arrays with the potentially maximum number of elements or use the standard container std::vector.

the code that you just showed has a problem.
You print only M because you didn't do the input for-loop for the N array. So the array N has nothing inside.
So to fix this do another for and ask for input in the array N.
for (int i = 0; i < m; ++i)
{
std::cin >> N[i];
}
Hope this helps.

Related

Garbage value when trying to remove value from dynamic array

i keep getting garbage value on one of the indexes in the dynamic array when i try to remove a value which was entered by user from a list of elements in the dynamic array.
used pointer as function parameters and replaced the value to be removed with 0 and by using a counter and for loop tried to skip all the 0s but in place of zero theres a garbage value.
#include<iostream>
#include<fstream>
using namespace std;
int size = 0;
int final = 0;
int* read(ifstream& a){
int temp;
a.open("data(1).txt");
while (!a.eof()){
a >> temp;
size++;
}
a.close();
a.open("data(1).txt");
int* arr = new int[size];
for (int i = 0; i < size; i++)
a >> arr[i];
return arr;
}
int* remove(int* a,int search){
for (int i = 0; i < size; i++){
if (a[i] == search)
a[i] = 0;
else final++;
}
int* change = new int[final+1];
for (int i = 0; i < size; i++){
if (a[i] > 0){
change[i] = a[i];
}
else continue;
}
delete[] a;
a = nullptr;
return change;
}
int main(){
int* ptr = nullptr;
int num;
cout << "please enter the number to remove: ";
cin >> num;
ifstream in;
ptr=read(in);
ptr=remove(ptr, num);
for (int i = 0; i < final; i++)
cout << ptr[i] << " ";
cout<<endl;
system("pause");
return 0;
}
There is much to discuss and critize about your code. Also your question is very unclear because we do not have your input file, nor do you tell us what the code should actually do. However, I will leave all "please write actual c++ rather than c without classes" aside and just point you to the one critical mistake:
This loop
int* change = new int[final+1];
for (int i = 0; i < size; i++){
if (a[i] > 0){
change[i] = a[i];
}
else continue;
}
And then this loop
for (int i = 0; i < final; i++)
cout << ptr[i] << " ";
It seems like you want to copy all elements that are >0 to change. Or maybe you want to copy all, its really hard to tell, because broken code is just broken, it does not explain itself. Anyhow...
The first loop leaves all elements change[i] where a[i] <= 0 uninitialized. The values at those indices i are indeterminate. There isn't really a value you can read. Attempting to read an indeterminate value results in undefined behavior.
You are attempting to read all elements of change, but some of them are not initialized, they are indeterminate values. Hence your code has undefined behavior.
There are other situations the will bring your code into bad states, like for example search not begin found in the input array or a[i] > 0 for some i > final. Though, I don't see a possiblity for any input to your code that would not eventually invoke undefined behavior.
You sould use a debugger to see where your code is doing something unexpected.

Problem outputting dynamic array from function [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
the function is to preserve argument array and produce anidentical array in the heap memory that has the even elements to (left) & odd(right), but when i output i find a row of zeros and bunch of random big numbers which look like addresses but I don't think they are, Please help.
int* even_left_odd_right(int arr[], int size1)
{
int* array;
array = new int[size1];
for(int i = 0; i < size1; i++)
array[i] = arr[i];
for(int i = 0, j =0; i < size1; i++)
{
if(array[i] % 2 == 0)
{
int temp = array[j];
array[j] = array[i];
array[i] = temp;
j++;
}
}
return array;
}
int main()
{
int size1;
cout << "Enter size of array:";
cin >> size1;
int* array1;
array1 = new int[size1];
int arr[size1];
cout << "Enter the entries in this array: ";
for(int i = 0; i < size1; i++)
cin >> arr[i];
even_left_odd_right(arr, size1);
for(int i = 0; i < size1; i++)
cout << array1[i] << " ";
delete[] array1;
return 0;
}`
The root cause of all your problems is that you do not use the return value of your function. Besides that, there are more things that should be corrected.
Additionally, we need to mention that what you are obviously learning now, dynamic memory management using new and delete and raw pointers for owned memory, is strongly discourage.
Basically: new, delete and raw pointers for owned memory should NEVER be used in C++.
It is that error prone that is has no place any more in standard C++. You even have an error with leaked memory and do not notice it. The array, that you are dynamically allocating in your function with new, is never deleted.
I know that teachers still do teach this crap, but just for explaining dynamic memory mangement from scratch. So, let's go ahead and use it for now.
You have however some additional errors.
Your function returns the partitioned data. But you never use the functions return value
You are using (for whatever reason??) a so called VLA (Variable Length Array) in int arr[size1];. This is illegal in C++. Real C++ compilers will not allow that.
You are mixing up arr and array1. In the beginning, you are creating array1. After creation, it is not initialized and will contain random values.
Then you call your function with arr and output array1 at the end. So, you will output random data. That is, what you see. Random data.
You could use the build in std::swap function. But I guess that it is prohibited by the teacher. What a shame.
You unneccessarily change the order of the entries in the array with swapping. But this does not harm
Your function simply returns a raw pointer. The outer world does not know anything about that. That is dangerous
You even do not know that arr in your function signature (int arr[]) will decay to a pointer
To quickly fix your code, we could write:
#include <iostream>
int* even_left_odd_right(int arr[], int size1)
{
int* array;
array = new int[size1];
for (int i = 0; i < size1; i++)
array[i] = arr[i];
for (int i = 0, j = 0; i < size1; i++)
{
if (array[i] % 2 == 0)
{
int temp = array[j];
array[j] = array[i];
array[i] = temp;
j++;
}
}
return array;
}
int main()
{
int size1;
std::cout << "Enter size of array:";
std::cin >> size1;
int* array1;
array1 = new int[size1];
//int arr[size1]; NOT ALLOWED in C++
std::cout << "Enter the entries in this array: ";
for (int i = 0; i < size1; i++)
std::cin >> array1[i];
int* array2 = even_left_odd_right(array1, size1);
for (int i = 0; i < size1; i++)
std::cout << array2[i] << " ";
delete [] array1;
delete [] array2;
return 0;
}
But such code should never be used in C++.
Again, I guess I understand requirements from teacher.
By the way. In C++17 you would probaly write the follwoing code:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
int main() {
// Tell user, what to do: Get the number of data to operate on
std::cout << "\nEnter the number of data to operate on: ";
// Read the number of data from the user via std::cin. Check, if number is OK
if (size_t numberOfData{}; (std::cin >> numberOfData) and (numberOfData > 0)) {
// Define the vector for our original data with the size given by the user
std::vector<int> dataOriginal(numberOfData);
// And get the number of specified data from the user
std::cout << "\n\nAnd now, please enter the data\n";
std::copy_n(std::istream_iterator<int>(std::cin), numberOfData, dataOriginal.begin());
// We want to preserve the original input, so, make a copy of that vector
std::vector result(dataOriginal);
// Now partition the output as requested
std::stable_partition(result.begin(), result.end(), [](const int i) { return (i % 2) == 0; });
// Show result to user
std::copy(result.begin(), result.end(), std::ostream_iterator<int>(std::cout, " "));
}
else {
std::cerr << "\nError: Wrong input given for number of data\n\n";
}
}
Please note:
No loops
Input validation
CTAD
No function needed, everthing can be done with one statemennt

insert value in dynamic array with loop using vector in c++

I want to insert value in dynamic array k. this is my code.
cin >> n;
std::vector<int> k;
for(int i = 0 ; i< n ; i++) {
cin >> k[i];
}
But it is not storing any value. I don't know why, please help me
Because vector is dynamic array, you should specify that you want to add a new element by using push_back instead of operator [].
Following piece of code would work:
for(int i = 0 ; i< n ; i++) {
int element;
cin >> element;
k.push_back(element);
}
Or even better you can initialise your vector object by calling the constructor which takes initial container size as an parameter. Later you always can add new elements to the vector again by using push_back.
cin >> k[i]; is trying to read into a location of the vector that does not exist yet (k is an empty container with zero elements).
You want to first read in the integer and then add it to the vector like so:
int num;
cin >> num;
k.push_back(num);
Alternatively you could resize k first, so it has elements at all indices you are going to access, by doing k.resize(n); after reading in n (or just create it with the right size right away) and then your existing code will be fine.
std::vector::operator[] does not resize the container. It only accesses pre-existing elements and if the accessed element is not within bounds of the container the behaviour is undefined.
You will need to use push_back in this case should be something like this:
#include <vector>
int main ()
{
std::vector<int> myvector;
int myint;
std::cout << "Please enter some Numbers (enter 0 to end):\n";
do {
std::cin >> myint;
myvector.push_back (myint);
} while (myint);
std::cout << "myvector stores " << int(myvector.size()) << " numbers.\n";
return 0;
}
This is a sample code but should give you the idea on how to get around with Vectors and push_back.
cheers
you don't need to take another variable just write
vector<int>k
for(int i = 0 ; i< n ; i++) {
k.push_back(i);
}

C++ segmentation fault array

In C++ I get a segmentation fault after telling the program how big the array should be (x).
Why is this happening and how do I fix this?
#include <iostream>
using namespace std;
int main()
{
int x;
cin >> x;
int array[x];
for (int *j=array; j; j++)
{
*j=0;
}
for (int *i=array; i; i++)
{
cin >> *i;
}
cout << array[3] << endl;
}
Your loop conditions are wrong.
for (int *j = array; j; j++)
and
for (int *i=array; i; i++)
will not stop at the end of the array, as the condition j (i) is true when traversing the array (i.e., to be false, the pointer needs to be nullptr). In fact, pointer arithmetic past the array boundary plus one results in undefined behaviour. Your stopping condition should be
i < array + x;
Moreover, variable length arrays are an extension and not support by the C++ standard. Use new[] instead to allocate memory, as #Joshua Byer pointed out.
int * array;
array= new int [x];
http://www.cplusplus.com/doc/tutorial/dynamic/
The conditions used in your loops are incorrect.
eg. for (int *j = array; j; j++) even though j will eventually reach the end of the array but will still never evaluate to false (allowing the loop to finish). On top of this it means you will iterate to past the end of the array and move into Undefined Behaviour, this is probably why you are seeing the segfault.
you either need to do the following (super gross solution!!!! also not C++ standard supported):
for (int i = 0, *j = array; i < x; i++, j++)
which will increment a counter and check the array at the same time as incrementing your pointer.
OR
USE VECTORS
std::vector is a much easier way to do what you are doing.
int arraySize;
cin >> arraySize;
std::vector<int> array(arraySize, 0);
for (int i=0; i < arraySize; i++)
{
cin >> array[i];
}
cout << array.at(3) << endl;
Here is a live example.
Within a for statement, the second expression should terminate the loop by evaluating to false. In this case however you never terminate the loop:
for (int *j=array; j; j++)
Instead do:
for (int *j=array; j < array + x; j++)
The expression array + x (by pointer arithmetic) means one element past the end of the array.
The above goes for both of the loops.

Program declaring variables by itself

I am still a ... novice, in c++.
I don't know the name of what I am looking for but
I 've been searching a lot but can't seem to find the answer to following question:
I want to write a program that would declare demanded number of variables.
Example:
int a;
cin>>a;
Now if "a" is 5 (or any other number), I want program to declare 5 more variables,
Names do not matter but let's say...n1,n2,n3,n4,n5.
I've tried array and for loop but can't get it to work.
I got answer on Croatian forum (forum.hr) but the forum is currently offline, so I had no
time to try it out...
It was about using heap instead of stack
Thx in advance
C++ has container classes for this purpose. In particular, you want a vector:
std::vector<int> a(size);
for (int i = 0; i < a.size(); ++i)
std::cin >> a[i];
Declares a vector a of integers of some size and reads its elements, one by one.
If this is C++, the best you can do is using std::vector as it will manage the memory for you.
you can store them in an array:
int a;
cin >> a;
int *number = new int[a]; // allocate an array of size a
for (int i = 0; i < a; i++) {
number[i] = 5 + i; // set your numbers to anything here
}
delete[] number; // otherwise you have memory leak
or better use a vector:
vector<int> number(a);
// iterate with a normal for loop
for (int i = 0; i < number.size(); i++) {
number[i] = 5 + i;
}
..
// or use iterators
for (vector<int>::iterator it = number.begin(); it != number.end(); ++it) {
cout << *it << endl;
}
so you don't have to manage memory.