Wrox Programmer Forums
|
All Other Wrox Books Do you have a question about a Wrox book that isn't listed anywhere on p2p.wrox.com or where the forum is locked? Here's a forum to post questions about any other Wrox book so that other readers or one of the authors can help you with your questions. IF YOU ARE LOOKING FOR CODE DO NOT ASK "Where can I find the code for this book?" That question is answered here.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the All Other Wrox Books section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
  #1 (permalink)  
Old June 8th, 2003, 11:18 PM
Registered User
 
Join Date: Jun 2003
Posts: 5
Thanks: 0
Thanked 0 Times in 0 Posts
Default Pointers and Arrays C++

In this little program I enter 10 integers and display them back
using arithmetical operation to a pointer.
it compiles, accepts my input, display the elements, but right after
that it causes an error. if I delete the "delete [] numbers" I will
be OK and if I use the pointer notation syntax "*(numbers + i)"
it works fine. here's the code...
can anyone explain me why? TIA

#include <iostream>

using namespace std;

int main ()
{
    const int max_value = 10;
    int* numbers = new int[max_value];
    int cnt = 0;

    do
    {
        cout << "\nPlease, enter integer #" << cnt + 1 << ": ";
        cin >> *(numbers + cnt);
        cnt++;
    }while (cnt < 10);

    for (int i = 0; i < max_value; i++, numbers++)
        cout << endl << *numbers << endl;

    delete [] numbers;

    cout << endl;
    return 0;
}
  #2 (permalink)  
Old July 10th, 2003, 01:45 PM
Registered User
 
Join Date: Jul 2003
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
Default

The reason is because your pointer variable is no longer pointing at the memory location you initialized using new.

In your for loop you are incremementing the location pointed to by the numbers variable. At the end of the loop numbers is pointing at a different location than where it started.

For this particular example to work I would add the following line of code at right after the for loop.

numbers -= max_value;






Similar Threads
Thread Thread Starter Forum Replies Last Post
C/C++ Pointers reality_42000 C++ Programming 1 March 4th, 2007 01:26 AM
array and pointers amrinder C++ Programming 1 November 10th, 2006 07:58 AM
pointers Stuby085 Visual C++ 1 August 30th, 2003 11:58 PM
Pointers jake VB How-To 12 June 21st, 2003 11:30 AM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.