Dynamic array from an input file - c++

I'm a beginner, so I'm sorry if this is really dumb question/problem.
The assignment that I have is printing out a dynamic array from an input file. I tried googling it and I found some similar problems... but the answers were all like "use vectors" etc but we haven't learned those yet. It's also said that a function must be used. This is what I came up with:
#include <iostream>
#include <fstream> //file input
using namespace std;
int *out(int *arr, int siz){
arr = new int[siz];
for (int i = 0; i < siz; i++) {
cout << arr [i] << " ";
}
return arr; //this should print out the array later???
}
int main(){
int siz;
int *arr;
ifstream inf ("input.txt");
inf >> siz; //
for (int i = 0; i < siz; i++) {
inf >> arr[i];
}
inf.close();
cout << "This array contains following elements: ";
*arr = *out(arr, siz) ;
delete[] arr;
return 0;}
So, it doesn't give any errors with Dev-C++ but when I try to run it, it crashes. I tried debugging it and then it gave me "segmentation error" or something like that. Then of course, I googled it and there must be something wrong with the pointers, right? Could you help me out? Thanks.

You are trying to access arr, when arr has not been allocated or initialized to a valid array. Your main needs to allocate arr before using arr to populate elements:
So, here's the changed version:
#include <iostream>
#include <fstream> //file input
using namespace std;
void out(int *arr, int siz){
for (int i = 0; i < siz; i++) {
cout << arr [i] << " ";
}
}
int main(){
int siz;
int *arr;
ifstream inf ("input.txt");
inf >> siz;
arr = new int[siz]; // added
for (int i = 0; i < siz; i++) {
inf >> arr[i];
}
inf.close();
cout << "This array contains following elements: ";
out(arr, siz);
delete[] arr;
return 0;
}

arr is an uninitialized pointer.
Do arr = new int[size]; before you read data into arr.

You haven't allocated memory to the array, which you'd likely need to do with malloc. Once you've read in the size of the array, allocate the memory.
inf >> siz;
arr = malloc(siz * sizeof(*int));
//Rest of program
//delete[] arr; <- you use this with the new keyword
free(arr); //Use 'free' with malloc
return 0;

I think what you want might be sth like this
#include <iostream>
#include <fstream>
int main(){
int siz(0);
std::ifstream inf ("input.txt");//Assume that the input file and this file are in the same folder
inf >> siz; //Assume that the first number in input file is the size of array
int *arr=new int[siz];
for (int i = 0; (siz-i)&&inf ; ++i) {
inf >> arr[i];
}
inf.close();
std::cout << "This array contains following elements: ";
for (int i = 0; siz -i ; ++i ) {
std::cout << arr [i] << " ";
}
delete[] arr;
return 0;
}

Related

when inputting a array the length of array replacing the first element in the array in c++ [duplicate]

This question already has answers here:
How do I use arrays in C++?
(5 answers)
Closed 1 year ago.
When inputting a array in c++ the element in 0th position will become the length of the array.
have two functions to input and print the array when print function calls the output array has always the array length in 0th position.
#include<iostream>
using namespace std;
int getArray(int array[])
{
int len;
cout << "Enter the length of the array" << endl;
cin >> len;
cout << "Enter the elements in the array" << endl;
for (int i = 0; i < len; ++i)
{
cin >> array[i];
}
return len;
}
void printArray(int array[], int len)
{
for (int i = 0; i < len; i++)
{
cout << array[i];
}
}
int main(int argc, char const *argv[])
{
int array[] = {};
int len = getArray(array);
printArray(array, len);
return 0;
}
In C++, the size of an array must be a compile time constant. So you cannot write code like:
int n = 10;
int arr[n]; //incorrect
Correct way to write this would be:
const int n = 10;
int arr[n]; //correct
For the same reason the following code (last statement) is incorrect :
int k;
cin >> k;
int arr[k]; //incorrect because k must be a compile time constant
You can see that this results in a problem here.
You should use std::vector for this purpose.
Using std::vector, your implementation would look like:
#include<iostream>
#include <vector>
using namespace std;
//passing vec by reference
int getArray(std::vector<int> &vec)
{
int len;
cout << "Enter the length of the vector" << endl;
cin >> len;
cout << "Enter the elements in the vector" << endl;
int element;
for (int i = 0; i < len; ++i)
{
cin >> element;
vec.push_back(element);//use push_back to add element to vector
}
return len;
}
//passing vec by reference
void printArray(std::vector<int> &vec, int len)
{
for (int i = 0; i < len; i++)
{
cout << vec[i]<<std::endl;//use vec[i] to access ith element
}
}
int main()
{
std::vector<int> vec;
int len = getArray(vec);
printArray(vec, len);
return 0;
}
You can see the output here.
Note
You can simply take the input in the main() itself instead of calling another functions. Similarly for printing the vector. But i have given the code according to your implementation.

How to implement a function which allocates in dynamic way memory for one-dimensional array of integers in C++?

How can we implement the function void v_alloc_table_add_5 (int iSize), which allocates memory in a dynamic way for a one-dimensional array of int variables?
The size of an array is specified by the iSize parameter. The array elements should be initiated on offset+5. Limitations are:
When array is allocated and initialized, display all array elements.
Remember that you need to deallocate memory using delete before end of the program.
The function should be protected against an invalid iSize parameter value.
My Code so far:
#include <iostream>
using namespace std;
void v_alloc_table_add_5(int iSize)
{
int *myarr = new int[iSize];
for (int i = 0; i < iSize; i++)
{
myarr[i] = 4;
}
for (int i = 0; i < iSize; i++)
{
cout << "Elements are: " << myarr[i] << endl;
}
delete[] myarr;
}
int main()
{
cout << "Array size?" << endl;
int input;
cin >> input;
const int iSize = input;
v_alloc_table_add_5(iSize);
return 0;
}

What are the rules for function returning pointer in c++ did I miss something in my code?

I want to create a function which generates an array(filled with random numbers) of the size I give as an input and the function returns the address of the first element of the generated array. I wrote the code as best as possible without any errors or warning. But at the runtime, the program crashes. I try to debug it but the debugger also froze and do nothing. I think the problem is in returning the pointer. Please help.
#include<iostream>
#include<cstdlib>
using namespace std;
int** the_gen(int num)
{
srand(1000);
int *ptr= new int(num);
int** const dptr=&ptr;
for(int i=0;i<num;i++)
{
*ptr= rand();
ptr++;
}
return dptr;
}
int main()
{
cout<<"Size of array:"<<endl;
int size_of_array;
cin>>size_of_array;
int **a;
a=the_gen(size_of_array);
for(int i=0;i<size_of_array;i++)
{
cout<<**a<<",";
a++;
}
}
you were using int** unnecessarily. only need to use that if you're creating an array of int pointers or a 2d array of int's:
the following code does what you're after i think:
#include<iostream>
#include<cstdlib>
using namespace std;
int* the_gen(int num)
{
srand(1000);
//edit
int *ptr = new int[num];
int* const dptr = ptr;
for (int i = 0; i < num; i++)
{
*ptr = rand();
ptr++;
}
return dptr;
}
int main()
{
cout << "Size of array:" << endl;
int size_of_array;
cin >> size_of_array;
int *a;
a = the_gen(size_of_array);
for (int i = 0; i < size_of_array; i++)
{
cout << *a << ",";
a++;
}
}
I think returning pointer is always bad idea, we should take memory pointers as a parameter as the follow
void the_gen(int num, int** arry)
{
srand(1000);
int *ptr = new int[num];
*arry = ptr;
for (int i = 0; i < num; i++)
{
ptr[i] = rand();
}
}
int main()
{
cout << "Size of array:" << endl;
int size_of_array;
cin >> size_of_array;
int *a;
the_gen(size_of_array, &a);
for (int i = 0; i < size_of_array; i++)
{
cout << a[i] << ",";
}
}

Segmentation fault in a program that reverses a dynamically allocated array

I was doing a test and the online test engine showing segmentation error, which is confusing because with no further details, and I checked the pointer no NULL and they work pretty fine, but don't how array here works. Because when debugging, everything is fine, until I try to cout/print out the array. it's reporting a is crushed here and break. I can do nothing here if it break, and I hit break or continue. if I continue, it runs just fine. so I was really confused.
My computer is windows 7, I run code in visual studio 2010 c++.
Debugging is not that clear to solve the problem, and I am learning c++ not very efficient.
Solve with Array need dynamic allocation.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
void reverseArray(int size, int num[]) {
if(size>1) {
int *p = &num[size-1];
int *f = num;
for(int i = 0;i < size/2; i++){
swap(*p, *f);
p--;
f++;
}
}
}
int main() {
int len;
int a[len];/This is the bug, can't use uninitialized var assign array/
cin >> len;
for(int i = 0; i < len; i++){
cin >> a[i];
}
reverseArray(len, a);
for(int i = 0; i < len; i++){
cout << a[i] << " ";
}
return 0;
}
This has something to with dynamic allocation, when I work in java, I create a new array.
I have to
int[] newArray = {2,4,1,2,3};
or
int[] newArray = new int[] {2,4,1,2,3};
Finally, this problem is solved, which makes me very happy.
Reading and learning is very important, coding is also important.
Thanks all,
And using vector instead of using array.
It would be easier.
#include <cstdio>
#include <vector>
#include <iostream>
using namespace std;
int main() {
int a;
int len;
vector<int> myvector;
cin >> len;
for(int i = 0; i < len; i++){
cin >> a;
myvector.push_back(a);
}
reverse(myvector.begin(), myvector.end());
for(int i = 0; i < len; i++){
cout << myvector[i] << " ";
}
return 0;
}
Using Array again(I doubt the following code):
#include<iostream>
//#include<cstdlib>
using namespace std;
void reverseArray(int size, int nums[]){
if(size > 1){
int *p = &nums[size-1];
int *q = nums;
for(int i = 0; i< size/2; i++){
swap(*p, *q);
p--;
q++;
}
}
}
int main(){
int len;
cin >> len;
int *a = new int[len];//a point to the first ele.
for(int i = 0; i< len; i++){
cin >> a[i];
}
reverseArray(len, a);
for(int i = 0; i < len; i++){
cout << a[i] << " ";
}
delete [] a;
return 0;
}
It worked perfect on my laptop, which is confusing because a is pointer, but I use it like an array. It shouldn't be working......
Final Array version:
http://ideone.com/ZMsD35
Done perfectly.
#include<iostream>
using namespace std;
int main(){
int len;
cin >> len;
int *a = new int[len];
for(int i = 0; i< len; i++){
cin >> a[i];
}
reverse(a, a+len);
for(int i = 0; i< len; i++){
cout << a[i];
}
delete [] a;
system("pause");
return 0;
}
The most likely reason for a segfault is the input. When the testing software passes len of size sufficient to overflow the automatic storage area, your program crashes on this line:
int a[len];
The exact value of len is system-dependent, but an input of 1,000,000 should do it on most common systems.
The fix is really straightforward - replace the declaration with
int a* = new int[len];
This will place the data in dynamic memory, rather than the automatic memory. It will also make your program standard-compliant, because variable-length arrays in C++ are an extension to standards.
Don't forget to delete a once you are done to avoid memory leak:
delete[] a;

dynamically allocated arrays with user input c++

I want to have a mini function that allows the user to type a group of numbers, and each of them will be dynamically allocated into an array. For example:
int main()
{
int* x = NULL;
int n, numbers;
std::cin >> n;
x = new int[n]
for (int i=0;i<n;i++){
std::cin >> numbers;
x[i] = numbers;
}
delete [] x;
So when the user types in
3
The user will be able to type in 3 numbers following that
3 1 2 3
I am trying to store the values 1, 2, 3 into an array so it will look like
[1, 2, 3]
but right now it's storing as
[123]
Anyway i can fix this? I'm new to C++ programming so I feel like there's an easy solution to this but i'm not sure how.. thank you!
You could store each element of the array directly into x[i]. Not sure what numbers is used for (I've assigned numbers from x[i]).
x is the array that is to be deleted. And there is a missing ; at x = new int[x] - is that a typo?
int main()
{
int* x = NULL;
int n, numbers;
std::cin >> n;
x = new int[n];
for (int i=0;i<n;i++){
std::cin >> x[i];
numbers = x[i];
}
delete [] x;
You can use a vector instead:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> v;
for (int i = 0; i < n; ++i)
{
int val;
cin >> val;
v.push_back(val);
}
}
C++'s vector takes care of memory allocation for you. You could then simply traverse it and print its contents.
cout << "[";
for (int i = 0; i < v.size(); ++i)
{
if (i != 0)
cout << ",";
cout << v[i];
}
cout << "]";
Example 1
int main()
{
int* x = NULL;
int n, numbers;
std::cin >> n;
x = new int[n]; // need a semi-colon here
for (int i=0;i<n;i++)
{
std::cin >> numbers;
x[i] = numbers;
}
for (int j = 0; j < n; ++j)
{
std::cout << "x[" << j << "] = " << x[j] << std::endl;
}
delete [] x; // you mean x, not a
return 0;
}
Once you fix (what I assume are just typos), what you have works fine. However, unless this is for an assignment, you should consider using std::vector instead of raw dynamic memory allocation. Doing so would reduce your code to about 4 lines.
int main()
{
std::vector<int> myvector;
std::copy(std::istream_iterator<int>(std::cin), std::istream_iterator<int>(), std::back_inserter(myvector));
std::copy(myvector.begin(), myvector.end(), std::ostream_iterator<int>(std::cout, "\n"));
return 0;
}
or, in C++11
int main()
{
std::vector<int> myvector{std::istream_iterator<int>(std::cin), std::istream_iterator<int>()};
std::copy(myvector.begin(), myvector.end(), std::ostream_iterator<int>(std::cout, "\n"));
return 0;
}
Why not just create the array dynamically? This way, the user won't have to type in the number of elements in advance:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vec;
int x;
while (cin >> x)
vec.push_back(x);
for (int y: vec)
cout << y << ' ';
cout << '\n';
}
The cout statements are just to illustrate that everything worked.