Now i have an array, P[8]={0,1,1,2,0,3,1,0}

And i want to add 4 separate values to each element in the array,so if i was to lookup P[2] i can access its 4 values.

I tried doing it by giving those standard values an array of itself and making each value get it through a loop but a fundamental problem occurs when assinging P[6] to those 4 values cause it kind of makes the array size 6,anyway i think i've got some concept confused.Is it possible ? How do i circumvent it ?

Recommended Answers

All 4 Replies

It looks like you want a 2D array:

int P[] =
{
    {0, 1, 1, 2},
    {0, 3, 1, 0}
};

for (int x = 0; x < 2; ++x)
{
    for (int y = 0; y < 4; ++y)
        cout << P[x][y] << ' ';
    cout << '\n';
}

Is that right? Or am I missing something that makes your problem not so simple? :(

If the size is determined at runtime you need a full fleged dynamic memory version. Something like

#include <iostream>


int **allocs(int x,int y){
  int **ret  = new int*[x];
  for(int i=0;i<x;i++)
    ret[i] = new int[y];
  return ret;

}


int main(){
  int **array = allocs(4,5);
  int p = 0;

  for(int i=0;i<4;i++)
    for(int j=0;j<5;j++)
      array[i][j] = p++;

}

>If the size is determined at runtime you need a full fleged dynamic memory
>version. Something like

A full fledged dynamic memory version? Is that what you call your program you just posted.
It would be so much better to rely on the standard headers than your memory leaking program.

To OP: Apart from Tom Gun advice, you may want to consider an array of a structure:

#include <iostream>
struct myStruct{
    int firstVal;
    float secVal;
    char thirdVal;
    long fourthVal;
};
int main(){

    myStruct P[]= {{0,  1.1,  'a',  14554},
                   {2,  2.1,  'b',  14254},
                   {4,  4.1,  'c',  14254},
                   {1,  8.1,  'd',  14254},
                   {1,  1.5,  'e',  14154},
                   {0,  1.4,  'f',  14214},
                   {2,  1.4,  'g',  14224},
                   {9,  1.7,  'h',  13254}
                  };
    std::cout<<P[6].firstVal;
};

This would allow you to use heterogeneous data types.
PS: If you need dynamic allocation techniques, consider a std::vector rather than hacks such has post#2

It would be so much better to rely on the standard headers than your memory leaking program.

Technically it leaks memory, but realistically, it is probably not going to be run on an OS that does not free memory when a process ends. As an example of how to allocate memory for a 2D array using new[], the code is fine.

It could be better, of course. :) As an example of both allocating and freeing, the code is more complete and even the technical memory leak is plugged. Good examples of heap memory should free as well as allocate. Here is the better code using the same style as monkey_king:

#include <iostream>


int **allocs(int x,int y){
    int **ret  = new int*[x];
    for(int i=0;i<x;i++)
        ret[i] = new int[y];
    return ret;

}


void deallocs(int **array, int x){
    for(int i=0;i<x;i++)
        delete[] array[i];
    delete[] array;

}


int main(){
    int **array = allocs(4,5);
    int p = 0;

    for(int i=0;i<4;i++)
        for(int j=0;j<5;j++)
            array[i][j] = p++;

    // check the array
    for(int i=0;i<4;i++){
        for(int j=0;j<5;j++)
            std::cout << array[i][j] << ' ';
        std::cout << '\n';
    }

    deallocs(array, 4);

}

I think direct heap allocation should be a last resort. There are so many safer and easier ways than allocating memory yourself, and it takes too much brainpower to make sure that you are not introducing any bugs with your memory handling. A big source of bugs comes from manually handling your memory. That is why the newer languages have garbage collection.

you may want to consider an array of a structure:

If you need dynamic allocation techniques, consider a std::vector

Good advice all around, but I would advise being careful about overengineering. Programmers are good at adding bells and whistles that do nothing but make the whole program more complex. All in the name of 'future proofing' or 'being robust', even when the value of that added complexity is questionable.

The vector class is cool, and you can use it to replace arrays most of the time. Here is the same code I posted using a vector. For the same job, it is both more work and more code to do the extra work, if just a little:

typedef vector<int> IntVec;
typedef vector<IntVec> IntVec2D;

int data[] = {0, 1, 1, 2, 0, 3, 1, 0};
IntVec2D P(2);

P[0] = IntVec(data, data + 4);
P[1] = IntVec(data + 4, data + 8);

for (IntVec2D::size_type x = 0; x < P.size(); ++x)
{
    for (IntVec::size_type y = 0; y < P[x].size(); ++y)
        cout << P[x][y] << ' ';
    cout << '\n';
}

C++0x will make that painful initialization step easier and more like the array version. But my point is that sometimes all you really need is an array. If there are only 8 values, heap memory is an extra point of failure and another thing to worry about. If the values are only ints, code to handle heterogeneous types adds no value. 'What if?' by itself is not a good reason to add complexity.

I think a better defense for the array of structs is abstraction. If the values are in groups of 4, they're related somehow, and wrapping them in an object might make the code using the groups more clear:

class Group // placeholder for a better name
{
    int _data[4];
public:
    // placeholder for a better constructor
    Group(int a, int b, int c, int d)
    {
        _data[0] = a;
        _data[1] = b;
        _data[2] = c;
        _data[3] = d;
    }

    friend ostream& operator<<(ostream& os, const Group& g)
    {
        for (int x = 0; x < 4; ++x)
        {
            os << g._data[x];

            if (x < 3) os << ' ';
        }

        return os;
    }
};

Group P[] = 
{
    Group(0, 1, 1, 2),
    Group(0, 3, 1, 0)
};

for (int x = 0; x < 2; ++x) cout << P[x] << '\n';

It is up to the programmer to decide if the abstraction is worth the code needed to implement the abstraction. dchunt did not give enough detail to know if an abstraction is worth the effort. It is possible that all he needs is an array, and anything more is unnecessary fluff.

Another situation came to mind when writing this post. If dchunt needs P to stay a 1D array, a second array of pointers into P can be used to achieve the same effect as a 2D array:

int P[] = {0, 1, 1, 2, 0, 3, 1, 0};
int *q[] = {&P[0], &P[4]};

for (int x = 0; x < 2; ++x)
{
    for (int y = 0; y < 4; ++y)
        cout << q[x][y] << ' ';
    cout << '\n';
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.