I have a pointer array (ptrArr1
) with two elements. I want the pointer array to be dynamically allocated. I can assign an address to the first element of the pointer array just fine, but I do not know how to assign an address to the second element of the pointer array. I do not wish to use any STLs or other precoded functions. I'm am doing this exercise to enhance my understanding of pointers. Thank you.
int main()
{
int one = 1;
int two = 2;
int *ptrArr1 = new int[2];
ptrArr1 = &one;
ptrArr1[1] = &two; //does not work
ptrArr1 + 1 = &two; // does not work
delete[]ptrArr1;
return 0;
}
To create a variable that will point to a dynamically allocated array, declare it as a pointer to the element type. For example, int* a = NULL; // pointer to an int, intiallly to nothing. A dynamically allocated array is declared as a pointer, and must not use the fixed array size declaration.
When we allocate dynamic array like this: MyArray * myArray = malloc(10 * sizeof (myArray) ); then we access the memory location by using dot(.) operator like this : myArray[0].
Dynamic memory allocation is to allocate memory at “run time”. Dynamically allocated memory must be referred to by pointers. the computer memory which can be accessed by the identifier (the name of the variable).
Dynamically allocating an array of pointers follows the same rule as arrays of any type: type *p; p = malloc(m* sizeof *p); In this case type is float * so the code is: float **p; p = malloc(m * sizeof *p);
There is a difference between an array of integers and an array of pointers to int
. In your case ptrArr1
is a pointer to an array of integers with space for two integers. Therefore you can only assign an int
to ptrArr1[1] = 2
but not an address. Compare
int xs[] = { 1, 2, 3 }; // an array of integers
int y0 = 42;
int *ys[] = { &y0, &y0 }; // an array of pointers to integers
Now you could also have pointers pointing to the first element of xs
resp. ys
:
int *ptr_xs = &xs[0];
int **ptr_ys = &ys[0];
// which can be simplified to:
int *ptr_xs = xs;
int **ptr_ys = ys;
For the simplification step you should look into What is array decaying?
You have an int array, not a pointer array. You can create a pointer array using
int **ptrArr1 = new int*[2];
and then assign the pointers to each pointer in the array:
ptrArr1[0] = &one;
ptrArr1[1] = &two;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With