Dynamic memory allocation

Hi all

I have a problem where I would like to dynamically allocate memory in the following way:

Lets say I have a for loop, and on every loop I want to create on more type int variable, for one more piece of info that I just got in a loop, I don't know how many pieces of info I would have to store so therefor I want to dynamically allocate it in every step of the loop, so basically I want to have:

pseudocode:
1
2
3
4
int info[not yet known];
loop1... info now holds 4  bytes (1 int)
loop2... info now holds 8  bytes (2 int)
loop3... info now holds 12 bytes (3 int)


It must be possible to do this (not in some complicated algorithm), but in all the tutorials that I've checked not one has given me the answer.

Thanks guys.
In C++?
I think what he needs is a vector ( http://cplusplus.com/reference/stl/vector/ )

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
27
28
29
30
31
32
33
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> info;

    while (true)
    {
        cout << "enter an int ('q' to quit): ";

        int temp;
        cin >> temp;

        if (!cin) break;

        info.push_back(temp);
    }

    cin.clear();
    while (cin.get()!='\n');

    cout << "\nyou entered:\n";
    for (int i=0; i<info.size(); i++)
    {
        cout << info[i] << ' ';
    }

    cout << "\nhit enter to quit...";
    cin.get();
    return 0;
}
Yes C++, sorry for not being clear.

First of all, while reading the code, I kinda understood why this is not all that simple, because the program doesn't know how much memory you'll be needing and therefor allocates a batch for you that you requested at THAT moment, but if you would want to keep on allocating one extra int every loop (stacking it up), the program would eventually come to a block, where the memory's already reserved. Am I anywhere close to being right?

So yes, thank you for the vectors, but just to be more clear, I'll write a simple idea (code):

1
2
3
4
5
6
7
8
9
10
	
	int *ptr = new int;
	
	for (i = 0; i < bignumber; i++)
	{
		num = (rand() % 10) + 1;
		if (bignumber % num  == 0) 
			*(ptr+1) = num;
	}


So in this case we would need to increase the mem alloc to ptr every time we fell in the if statement, but we don't know how big the size we would need, so I would like to allocate one more int to ptr when needed, like:

_ <- size of memory pointed to by ptr:
0x941F <- just an example address location pointed to by ptr.

0x941F. _,
0x941F. _ _,
0x941F. _ _ _,
0x941F. _ _ _ _ ,
0x941F. _ _ _ _ _,

I think you get the point.

Now as I said in the beginning, after some thought I don't think this is something simple and everyday as I had hoped it would be.

Thanks again.
Thanks m4ster r0shi

Vectors as it would seem after the initial read, are exactly what I was looking for.

Cheers.
Topic archived. No new replies allowed.