By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,918 Members | 2,240 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,918 IT Pros & Developers. It's quick & easy.

C++ Code

P: 5
What is wrong with this code?
Expand|Select|Wrap|Line Numbers
  1. int *array (int n)
  2. {
  3.     return new int(n);
  4. }
  5.  
  6. int main()
  7. {
  8.     int *p = array(10);
  9.  
  10.     for(int i = 0; i < 10; i++)
  11.     {
  12.         p[i]= 0;    // initialize all to 0
  13.     }
  14.  
  15.     printf( "%d\n", p[0]);
  16.     p = array(10);
  17.     printf ("%d\n", p[0]);
  18.     return 0;
  19. }
  20.  
Mar 19 '07 #1
Share this Question
Share on Google+
9 Replies


RedSon
Expert 5K+
P: 5,000
Is this an assignment, try to find the problems in the code? Next time you should use CODE tags.
Mar 19 '07 #2

P: 5
yes, try to find problem
Mar 19 '07 #3

Ganon11
Expert 2.5K+
P: 3,652
We won't do your homework for you. What do you think is wrong with it?
Mar 19 '07 #4

P: 5
I think there is a problem with the array function, it should return new array if integers.

// CODE

int *array (int n)
{
return new int(n); // should be new int[ ];
}
//

Am I wrong?
Mar 19 '07 #5

Ganon11
Expert 2.5K+
P: 3,652
That's one of the problems I spotted - there is one other similar to this one somewhere else in the code.
Mar 19 '07 #6

P: 5
Dynamic allocation, using delete [ ] array?
Mar 19 '07 #7

Ganon11
Expert 2.5K+
P: 3,652
Yes, that would be the other problem.

If you add these two things, do you think the code will work? Try running it through a compiler to see if it does work as expected.
Mar 20 '07 #8

P: 5
It compiles, first printout is 0 and the second is some address like -84551551.
But the program gives the same result without delete [ ] array.
I think it is good, it is always good to use delete.
Mar 20 '07 #9

Ganon11
Expert 2.5K+
P: 3,652
I'd say that's correctly working now. The first result is the correct value, as the array returned by the function is filled with 0s. The second result is expected, too, because a new array is created, but not filled.

Do you think it is a problem that the second array is never filled, or that the first array is not deleted?
Mar 20 '07 #10

Post your reply

Sign in to post your reply or Sign up for a free account.