0

I am new to c++ and i was trying to do folloing two things without help of std::vector( This was done earlier)

  1. Define an array of integer and the size of array is not known to me.
  2. 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];
    }
}
10
  • 1
    @Hennaldo Why the surprise? It seems to me like a perfectly valid thing to want from a test program. Commented Jan 16, 2013 at 9:16
  • 3
    what do you mean by "a single memory"? looking at the code, you will print out n 0'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. Commented Jan 16, 2013 at 9:19
  • 8
    for(int i =0;i<n;++n) --> ++i ? Commented Jan 16, 2013 at 9:20
  • 2
    While it's good to learn the basics of a language, once you know how to handle arrays you should stop using them and start using 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. Commented Jan 16, 2013 at 9:25
  • 2
    FWIW: you don't need the initialization loop. new int[n]() will zero initialize all of the int. Commented Jan 16, 2013 at 10:02

1 Answer 1

3

I’m not sure I understand all yours problems but the typo for(int i =0;i<n;++n) in testFunction led to a very long loop.

Write:

for(int i =0;i<n;++i) 

this print yours n "0"

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.