5

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;

}
Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
Robin Alvarenga
  • 321
  • 2
  • 14
  • 1
    When you do `ptrArr1 = &one` it's similar to doing `one = two` and expecting the value of `one` to still be `1`. – Some programmer dude Nov 20 '18 at 07:59
  • 1
    Furthermore, `ptrArr[x]` is an `int` and not an `int*` (which e.g. `&one` is). – Some programmer dude Nov 20 '18 at 07:59
  • 1
    `ptrArr[1] = &two;` tries to assign an address (`int*`) to an `int` -> type mismatch. `ptrArr1 + 1 = &two;` is not a type mismatch but tries to assign an address to a non-lvalue. Strongly simplified, this is as wrong as `1 = 0;`. – Scheff's Cat Nov 20 '18 at 07:59
  • Also you have `int *ptrArr1 = new int[2];` and right after `ptrArr1 = &one;` which overwrites `ptrArr1`. It's kind of like writing `foo = 2; foo = 42;`. – Jabberwocky Nov 20 '18 at 08:27

2 Answers2

6

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?

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
3

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;
eozd
  • 1,153
  • 1
  • 6
  • 15
  • 2
    Thanks eozd! The use of '**' is completely new to me, but it lets me do what I wanted to accomplish. – Robin Alvarenga Nov 20 '18 at 08:09
  • @CarlosRobinAlvarenga If eozd answered your question (IMHO, she/he did), please, don't forget to [accept](https://stackoverflow.com/help/someone-answers) it. – Scheff's Cat Nov 20 '18 at 08:50