0

Good morning everybody. I have tried to fill an array with elements enterd by the user; the problem is that while I have already found an answer to this on the internet, it says that my code should work, but it doesn't. Specifically, the computer says that the program stopped working after I try to run it, and honestly I don't really understand where I made a mistake. The code is the following:

#include <iostream>
using namespace std;

void getarray (int[],int);
void print (int[],int);

int main(){
    const int size=10;
    int n[]={0};
    getarray (n,size);
    print (n,size);
}

void getarray (int n[],const int size){
    cout<<"Insert elements to fill the array:\n";
    for (int i=0;i<size;i++){
        cin>>n[i];
    }
    cout<<"Filling completed.\n";
}
void print (int n[],const int size){
    cout<<"The inserted array is:\n";
    for (int k=0; k<size; k++)
        cout<<n[k]<<" ";
}

Used simply to get the array and print it.

1
  • What is the exact error message when your run your program? Commented Sep 11, 2016 at 11:38

2 Answers 2

5

The problem lies in your array declaration.

int n[]={0};

This tells the compiler that you want an array of size 1 with the element at n[0] initialized to 0. Further down the code you are going out of bounds as soon as i is bigger than 0.

int n[size];

Is probably what you are looking for here. If this is unclear do read http://www.cplusplus.com/doc/tutorial/arrays/

Sign up to request clarification or add additional context in comments.

Comments

0

The problem is that you have declared your array n in main() as:

int n[] = {0};

What this statement does is declare an array n and initialize it. As you can see, you're initializing the array with just one element, which is "0". This way of declaration delegates the responsibility of creating an appropriately sized array to the compiler as per how much elements are being used in the array initializer statement. For example:

int foo[] = {1, 2, 3, 4};

would create an array foo that has memory enough to hold at most 4 integers.

Thus, what your code does is effectively creates an array that holds only 1 integer.

Now when you access the array n in your functions, you try to access the array with indices > 0. In other words, the array being a single-element array, n[1], n[2] etc. are out of bounds, and would result in accessing random locations resulting in undefined behaviour (and program crash as well!).

What you are probably looking for is

int n[size];

which will create an array with enough memory to hold 10 integer elements.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.