# Accessing values in arrays pointed to by a pointer array. (C++)



## TheUnlimited (Dec 12, 2005)

So, I guess I feel like kind of a jerk coming here for this. But looking around the rest of the forums, I think this could be a nice new haunt. ^_^

Anywho...I'm having a bit of trouble figuring out how to properly manipulate an array of pointer values that each point to another array. My knowledge of C++ is mediocre at best, and after much searching, I can't seem to lock onto a solid answer for this. My books aren't being very helpful either.

This is a tiny but critical portion of a larger project. I'm not asking for a full-blown code or anything, just some assistance in how to manage and manipulate these arrays properly.

Let's say I make a pointer array: int* mooPoint[4].

Next, I create an integer array pointed to by mooPoint[0], using the new command: mooPoint[0] = new int[10]. Each pointer in mooPoint[] will point to a different array.

Here's where I get caught up. I'd like to access the third value (new int[2]) in the array pointed to mooPoint[2]. Maybe I want to write a value, or print a value, or copy it into something else. I just need to access that value, or any given value for that matter in any of the arrays.

Example:
/******************************************/
int* mooPoint[4];

for(int i = 0; i < 4; i++)
{ mooPoint_ = new int[10]; }

//copy int value "x" into position [2] in the array pointed to by mooPoint[2]
????? = x;
/******************************************/

I can't for the life of me figure out the proper syntax to do such a thing. I'm really stumped on this one, as I've never had to do anything quite like it before.

This is a critical launchpad for the rest of the project. Once I'm able to manipulate the arrays pointed to by a pointer array, it's all gravy. I am confident that once I know how to do this, I can complete the rest of the project as well. Knowing how to do such a simple thing as above, I should be able to devise how to load up the arrays, print them out, and otherwise maniplate them.

For reference, this is C++, I'm using MS Visual Studio 6.0, and running Windows XP.

Assistance is much appreciated, and thank you for even reading this far. ^_^_


----------



## mgoldb2 (Dec 16, 2004)

```
mooPoint[2][2]=7;
cout<<mooPoint[2][2]<<endl;
```
would put 7 in the spot you wanted in your code.

Usually it not decleared the way you did it even thoe your way works fine. Usually the code would look something like this.


```
#include <iostream> //for input  and output

using namespace std;

int main ()
{
	
int mooPoint[10][10];

mooPoint[2][2]=7;
cout<<mooPoint[2][2]<<endl;

return 0;

}
```


----------



## TheUnlimited (Dec 12, 2005)

Thank you very much, MGold. ^_^

It figures that it was something as simple as that, while I was sitting here thinking I'd need the dereference asterisk or the reference ampersand. 

I should be able to lift off from here, and knowing that it's really so simple is even better.

The particular reason I'm doing it that way is because each array will be of a variable size -- so one array may be 10 slots, and the next one may be 45.

Once again, you have my thanks.

EDIT: I guess I was rather misleading in my intentions, so here's a clarification on my initial little code blurb. The reason I don't simply make four arrays of different sizes is because the number of arrays is also random, although that is not shown in this code.


```
#include <iostream>

using namespace std;

int main ()
{
    int* mooPoint[4];  //create the array of pointers
    int n = 0;
    for(int i = 0; i < 4; i++)
    {
        n = rand();        //generate random number
        mooPoint[i] = new int[n];  //make an array of size n associated
                                   //with mooPoint[i]
    }

    int x = 930;

    //copy int value "x" into position [2] in the 
    //array pointed to by mooPoint[2]
    ????? = x;

    return 0;
}
```
Forgive me if my code isn't pristine. It's been ages since I've been given a coding assignment.


----------



## Cache (Dec 12, 2005)

The code posted by mygodlb2 should work fine. Just some notes:

When you declar an array by the following:

```
int* mooPoint[4];
```
You are making an array with 5 elements, not 4. Because array indexing starts at 0. 

0,1,2,3,4 = 5 elements.

The following code implements mygodlb2's advice, which complies and runs fine for me:


```
#include <iostream>

using namespace std;

int main ()
{
    int* mooPoint[4];  //5 element array
    int n = 0;
    for(int i = 0; i < 4; i++)
    {
        n = rand();        //generate random number
        mooPoint[i] = new int[n];  //make an array of size n associated
                                   //with mooPoint[i]
        
        //Initialize this array with a default value (0)
        for (int j = 0; j < n; j++) 
        {
            mooPoint[i][j] = 0;
        }
    }

    int x = 930;

    //copy int value "x" into position [2] in the 
    //array pointed to by mooPoint[2]
    mooPoint[2][2] = x;
    cout << mooPoint[2][2] << endl;
    
    return 0;
}
```
You can see I aslo give each element of the integer arrays a default value. This would make it easier to debug.

Now someone correct me if I'm wrong here, but I think another thing to note would be: Because you use rand() to generate the number of elements in the integer arrays, there is no guarantee mooPoint[2][_*2*_] actually exists. Since rand() returns an integer value between 0 and RAND_MAX (32767) -- the number of elements given to the array contained in mooPoint[2] may well only be 1.


----------



## mgoldb2 (Dec 16, 2004)

Cache said:


> You are making an array with 5 elements, not 4. Because array indexing starts at 0.
> 
> 0,1,2,3,4 = 5 elements.


This is wrong. int a[4] would declare a array with 4 elements

0,1,2,3 = 4 elements. YOU CAN NOT USE 4. it will compile and it even might give you the right answer sometimes but in most cases it should thow you a error.


----------



## Cache (Dec 12, 2005)

mgoldb2 said:


> This is wrong. int a[4] would declare a array with 4 elements
> 
> 0,1,2,3 = 4 elements. YOU CAN NOT USE 4. it will compile and it even might give you the right answer sometimes but in most cases it should thow you a error.


How right you are. Doesn't inspire much confidence for my first post on this forum lol.

EDIT: Seems I can't edit my other post to correct it either.


----------



## TheUnlimited (Dec 12, 2005)

I thank you both from the bottom of my heart. ^_^

Thanks for pointing out that mooPoint[2][2] may not even exist. There is a default minimum/maximum that I will set the RAND() to, so I'll have certain bounds. A separate array will be used to track the number of slots in each of the arrays during generation time, before the random number is overwritten.

You have my greatest gratitude, and hopefully this will allow me to complete the rest of the project. It's a very small part of it, and I won't bother you all with the rest of the details, but it's also a veritable cornerstone.

I probably won't be able to post again until after Wednesay, when it's due. Until then, thanks! ^_^/)


----------



## TheUnlimited (Dec 12, 2005)

I've got the project to do just about everything I need it to do, thanks to you guys. That really was a cornerstone for the whole thing. 8)

Another question, on related topic, though.

I need to make some random-sized pointer arrays now, but I'm constantly getting the errors:
error C2057: expected constant expression
error C2466: cannot allocate an array of constant size 0

From what I gather, you're not allowed to make arrays of a random size "on the fly." Unfortunately, that's exactly what I need to do, generate random-size arrays each time the program is run. I'm able to do this when using the "mooPoint_ = new int[n]" method, but not if I do something more like:


PHP:


int n = rand() % 50 + 100;  //bounded random number
int *mooPoint[n];

This little bit refuses to run. The random number won't be zero, and is a constant -- it's simply not hardcoded in.


PHP:


#include <iostream>
#include <ctime>

using namespace std;

int main()
{
	srand(time(NULL));  //seeds the random generator

	const int n = rand() % 100 + 50;  //bounded random #

	int *mooPoint[n];   //pointer array of size "const int n" defined by rand()

	cout<<n<<endl;

    return 0;
}


Any methods that I can use to "fool" the compiler? If all else fails, I can try to make a dynamic array function that could generate a random-sized bounded array..._


----------



## Sesshou (Dec 17, 2005)

Hm, random sized array?The compiler needs the size of an array...because they're getting their memory reserved even without initialization (afair)

I recommend using dynamically allocating your array (even though I'd go with blocky allocation,like always allocate medium sized chunks)

here's the code:

```
int main()
{
    srand(time(NULL));  //seeds the random generator 

    const int n = rand() % 100 + 50;  //bounded random #

	int * moo_point =0;               // ready up your future-array 

    moo_point = (int*) malloc(n * sizeof(int)) ;   //allocate memory base on ('n' * sizeof(int))

    memset(moo_point,0, (n* sizeof(int)));			// optionally initialize all array cells with 0's
													
    cout<<moo_point[0]<<endl; // manipulate your array as much as you like :P, range is always 0 to n-1
	cin >> moo_point[1];
	free(moo_point);					// free up the allocated memory after use
	moo_point = 0;						// make the now obsolete pointer 'unusable'
    return 0;
```
(edit: put the code in php tags)

Hope it helps~

(another edit: sorry I'm sleepy I guess my post is redundant :dead: , you already knew that ,right?
I'm at my limit of being awake, I'll take a look at your prob later...
but I think you can access pointers in your array using an ampersand , &moo_point[2] = 1; // sets the value in [&2] to 1...not sure...too sleepy)


----------



## TheUnlimited (Dec 12, 2005)

Thank you, MGold, Cache, and Sesshou. Those tiny little bits of proper programming knowledge that you guys imparted upon me allowed me to complete the rest of the project. They were a tiny but massively important aspect, and is all worked out in the end. ^_^


----------



## Sesshou (Dec 17, 2005)

I would have edited my post , but it seems that's only possible for a short time after you've posted...

This is what I've wanted to add:

- int * a; /pointer to an int,can be turned into an array by allocating memory
you can access those with either *a or a[n]

- int ** a; pointer to a pointer,both can be turned into arrays by allocating memory, access : *a[n],**a,a[n][n]

etc.
think of [n] as one step forward in pointers...
using pointers to pointer you can create all sorts of funky arrays

like
int ** a;

a[0][allocate 5 int pointers] (a[0][0] = new int[5]) access a[0][0-4];
a[1][allocate 10 int pointers] (a[1][0] = new int[10]) access a[1][0-9];
...
a[5][allocate 50 int pointers] (a[5][0] = new int[50]) access a[5][0-49];

etc...

you have to free the branches first,freeing the root array first would leak memory...

to free a 2 dimensional array like a[variable][variable] free a[0-(variable -1)]
then free a,

I didn't write the detailed code,since you've already finished your project, but I hope this information is still somewhat valuable to you :smile:


----------

