Dynamic struct of array

Hi,
I want choice dynamic size for array, and user can enter arbitrary size of n.
Similar this.
What i do? I don't like use pointer or any advanced code.(I need solution for beginners)
1
2
3
4
struct Test
{
	string test;
} arrtest[n];
Last edited on
Hey, um, you could try this, it's a beginner's solution only:
1
2
3
4
5
6
7
8
9
struct Test
{
 string test;
} arrtest[50];
int n;
cout<<"\n Enter the limit ";
 cin>>n;
for(int i=0;i<n;i++)
 gets(arrtest[i].test);

This way even if the structure has a size of 50, you're using only the require 'n' values.
Note: I am a beginner. (so my answer may not be correct)

It is not possible to have the user enter the size of an array without using a pointer/list type data structure. I am sure you will see an error if you try to compile saying something like "array cannot be initialized with a variable", and that is even if you have already initialized the variable BEFORE the array declaration.

I think it is something to do with how the program compiles. For every array defined, it allocates the necessary memory for it before moving to the next piece of code.

Addition: The only way I found around this in my earliest days was to simply create an array that is larger or as large as what could possibly be used. If this is a solution for beginners, there should be no harm in creating a large array, especially if the data is entered manually. Of course, you should probably tell the user the maximum size of the array and/or give a message only when more data than the allowable size is attempted.
Last edited on
Thanks,
If we use the best solution,How?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>
#include <vector>

struct Test
{
    std::string test;
}

std::vector<Test> global; //Creates an empty global vector of Test

int main()
{
    int n;
    std::cin >> n;
    std::vector<Test> local(n); //Creates vector of n Test structs
    global.resize(n); //global now stores n Test structs
    //Vectors can be easily used just like arrays:
    gobal[0] = "Hello";
    local[0] = "world";
    std::cout << global[0] << ", " << local[0] << '\n';
}
You can replace test with -> int, float, other class,..
1
2
3
4
5
6
7
8
9
10
#include "iostream.h"
int a =0;
cout << "size of array?";
cin >> a; 
Test * arr = new Test[a];


//no memory leak so...
delete [] arr;


it's called late binding
Last edited on
it's called late binding
It is called dynamic memory allocation.

late binding is a process of runtime selection of virtual functions:
http://bit.ly/1sqJBpv
Also, delete[] arr; (note the brackets)
Also, delete[] arr; (note the brackets)

Your absolutely right, thx ;)
Topic archived. No new replies allowed.