# Thread: How to change value of a referenced object.

1. ## 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. I am not too sure I understood your question (you see, smoking too much weed can do this to a person) but here goes...

ex.1
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

ex.2
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

ex.3
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

3. ## REPLY

REPLY........
We cannot do witout pointers.
The syntax is that
int *ptr;
int n;
cin>>n;
ptr=new int [n];
delete ptr;

4. If you want a dynamic array you could use STL vector (it will take care of the memory allocation for you).

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;
}
else
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