Dynamic Memory Allocation

sub unknown size... HELP!!!
Sub must be equal to the no. of lines.. (how to do it??)

#include <iostream>
using namespace std;

int limit(int&x) {
cout<<"Number of lines: ";
cin>>x;
return(x);
}
int l;
struct stud_rec
{
int data;
};
int main () {
int i;
limit(l);
stud_rec sub[]; //sub unknown size (need help on this line)
cout<<"\n";


Sub must have an equal size as the no. of lines.. (how to do it??)

Thank you in advance.....
Last edited on
Do it this way:

1
2
limit(l);
stud_rec sub[l];


Also why would you want to make 'l' a global variable?

Aceix.
it gives me an error expected constant expression, cannot allocate an array of constant size 0, sub: unknown size
Please use code tags when you post to make the code clean and readable, insert it beetween
[code ] [/code]

Here is a simple example of dynamic memory allocation regarding structs: ( apply it to your program )
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
#include <iostream>
#include <new>

struct X
{
    int data_;
};

int main ()
{
    std::size_t size;
    std::cout << "Enter Size: ";
    std::cin >> size;
    
    // declare a pointer to the struct X
    // and dynamically allocate memory
    X* pointer = new (std::nothrow) X [ size ];
    
    // exit if the allocation failed
    if( !pointer ) return 1;
    
    // now you can access the member of struct by :
    pointer[ 0 ].data_ = 100;
    
    std::cout << "\npointer[ 0 ]: " << pointer[ 0 ].data_;

    delete[] pointer; // deallocate memory
}

Last edited on
Whatabout using a pointer with the new operator?

Something like this:
stud_rec* sub=new stud_rec[l];

But do not forget to deallocate the memory.

HTH,
Aceix.
Last edited on
It worked guys!! THANKS :))
Topic archived. No new replies allowed.