Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning values to all the elements of a dynamically allocated pointer array?

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;

}
like image 482
Robin Alvarenga Avatar asked Nov 20 '18 07:11

Robin Alvarenga


People also ask

How do you assign values to a dynamically allocated array?

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.

How do you access elements of dynamically allocated arrays?

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].

Are pointers dynamically allocated?

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).

How do you allocate memory for array of pointers?

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);


2 Answers

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?

like image 176
Micha Wiedenmann Avatar answered Sep 28 '22 06:09

Micha Wiedenmann


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;
like image 40
eozd Avatar answered Sep 28 '22 05:09

eozd