Create array with values pointing to values of different array

As the title says, I have an array with a set amount of values and I am wanting to copy pointers of each value to a different array of identical size. This code creates the error " invalid conversion from 'int' to 'int*' ".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
char arrayOfChars[100];

int main()
{

    //set the values of the array of characters to an increasing amount of numbers
    for (int i =0; i < 100; i++)
    {

        arrayOfChars[i] = (char) i;
    }

    int* arrayOfints[100];
    //transfer to array of ints

    for (int i =0; i< 100; i++)
    {

        arrayOfints[i] = (int) &arrayOfChars[i];

        //check what the output is
        cout<< arrayOfints[i] << endl;
    }

    return 0;
}


Any idea what the code should be? Thanks in advance
Last edited on
The error is just what it says:
you are trying to convert an int to a pointer to int.

arrayOfints[i] = (int) &arrayOfChars[i];
Next time post the line the error occurs. Why do you use & here? You need the address?

One more thing. (int) is the C-way of casting.
Use static_cast<int> instead for a c++ way (more safe this way).
If I understand correctly, you want the second array's elements to point at those of the first array, so you can access the values in the first array using the pointers in the second?

If so, I think that using an array of int*s pointing at chars will cause problems. The value you end up displaying would be the int value corresponding to 4 adjoining chars (that is, in the 32-bit case: char = 8 bits, int = 32 bits, so int* thinks it's pointing at 32 bits = 4 chars worth of memory data).

So, using a char* array instead

1
2
3
char* arrayOfCharStars[100];
// store pointers
arrayOfCharStars[i] = &arrayOfChars[i];


and

1
2
// deref pointer (to char) and cast (to int) to display numaric value
cout<< (int)*arrayOfCharStars[i] << endl;


Edit: or being good (like eypros)

1
2
// deref pointer (to char) and cast (to int) to display numaric value
cout<< static_cast<int>(*arrayOfCharStars[i]) << endl;


Andy

P.S. Try

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    char test[4] = {'\x01', '\0x23', '\x45', '\x67', '\x89'};

    int* pint[2] = {0, 0};
    pint[0] = (int*)&test[0];
    pint[1] = (int*)&test[1];
    // note that = (int*)&test[2]; won't work, as the array is not long enough
    // to provide the extra 3 bytes require by the int*

    cout << "pint[0] = " << *pint[0] << " / " << hex << *pint[0] << dec << endl;
    cout << "pint[1] = " << *pint[1] << " / " << hex << *pint[1] << dec << endl;
  
    return 0;
}
Last edited on
Thanks for the awesome reply, I'm learning but its great to see some example code like this. Thanks again!
Topic archived. No new replies allowed.