I am new to c++ and i was trying to do folloing two things without help of std::vector( This was done earlier)
- Define an array of integer and the size of array is not known to me.
Pass this array into another function and output all the values stored in array.
int _tmain() { int* a = NULL; int n; std::cin >> n; a = new int[n]; for (int i=0; i<n; i++) { a[i] = 0; } testFunction(a,n); delete [] a; a = NULL; } void testFunction( int x[], int n) { for(int i =0;i<n;++n) { std::cout<<x[i]; } }
But i can see that its not allocating memory of 10 bytes and all the time a single memory is filled up with 0. Can anyone please help me if i am lacking something ? Or is there any alternative way for this apart from vector. Thanks in Advance
I modified with one thing as i realized that i put ++n instead of i
int _tmain()
{
int* a = NULL;
int n;
std::cin >> n;
a = new int[n];
for (int i=0; i<n; i++) {
a[i] = i;
}
testFunction(a,n);
delete [] a;
a = NULL;
}
void testFunction( int x[], int n)
{
for(int i =0;i<n;++i)
{
std::cout<<x[i];
}
}
n0's, because 0 is the value you assign each item in your for loop in main. You also won't get newlines or spaces between the 0's because you don't output those characters, so the 0's get printed next to each other.std::vector. It will still be possible for mistakes as the one you have here, but in general it will make your life as a programmer much, much easier if you use the standard containers.new int[n]()will zero initialize all of theint.