Thread: How to change value of a referenced object.

  1. #1
    Registered User
    Join Date
    Sep 2001

    How to change value of a referenced object.

    My book said that in order to use dynamic memory allocation (i.e. the new keyword), you needed to use pointers. As in:

    type name = new type[array size];
    so a) Is there a way to do this without pointers?

    b) If not, how do you change the value of the number?

    c) If there is an answer to B), can you do this with all pointers.

    Thanks in advance if you can help.

  2. #2
    Registered User Engineer's Avatar
    Join Date
    Oct 2001
    I am not too sure I understood your question (you see, smoking too much weed can do this to a person) but here goes...

    int x = 0; // the value of x is now equal to 0

    x = 4; // value of x changes to 4, and no pointers are involved

    int *x;

    x = (int)malloc(sizeof(int)); // x is now pointing to an int

    *x = 4; // the integer that x points to becomes 4

    free(x); // free the memory allocated

    int x = 0, *px; // integer x equals 0, and integer pointer px

    px = &x; // px is now pointing to x

    *px = 4; // the value of x is now 4

    Hope this helps
    1 rule of the Samurai Code: if you have nothing to say, don't say anything at all!

  3. #3
    Registered User
    Join Date
    Dec 2001


    We cannot do witout pointers.
    The syntax is that
    int *ptr;
    int n;
    ptr=new int [n];
    delete ptr;
    All is well that ends well

  4. #4
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    If you want a dynamic array you could use STL vector (it will take care of the memory allocation for you).

  5. #5
    int i;
    const int arraySize = 3;
    int * array = new int[arraySize];
    if(array = NULL)
    cout << "sorry not enough memory for an array of that size" << endl;
    for(i = 0; i < arraySize; i++)
    array[i] = 3 * i + 301;
    for(int i = 0; i < arraySize; i++)
    cout << arraySize << endl;
    delete [] array;

    Now you have to decide whether array is really a pointer or not. It usually boils down to semantics.

    If you declare dynamic memory for a single int, then use example supplied by Engineer, except substitute for new instead of the c style malloc(), if you wish.

    If your compiler supports STL, and you are familiar with vectors, by all means use them.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Installing Direct X
    By bumfluff in forum Game Programming
    Replies: 36
    Last Post: 11-15-2006, 07:18 PM
  2. Replies: 4
    Last Post: 11-14-2006, 11:52 AM
  3. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 12:13 AM
  4. A question about constructors...
    By Wolve in forum C++ Programming
    Replies: 9
    Last Post: 05-04-2005, 04:24 PM
  5. Replies: 2
    Last Post: 09-04-2001, 02:12 PM