Dynamic Array Struct ++

No errors and not working.
No idea what i've done and how to fix it...

I want that struct car contain 2 dynamic array members declared earlier by question "x"
1
2
3
4
5
6
7
8
9
10
11
12
  	int x;
	cout << "x" <<endl;
	cin >> x;
	
	string name[x];
	int year[x];	
		
	struct car
	{
		string *name;
		int *year;
	};


ideas?
Last edited on
closed account (E0p9LyTq)
Arrays, C style or the new C++ STL container, are compile time sized. You have to write potentially error-prone code to dynamically set the size at run time.

It is much better, and safer, to use a container such as vector.
Last edited on
Arrays, C style or the new C++ STL container, are compile time sized. You have to write potentially error-prone code to dynamically set the size at run time.

is there short answer why is that?

i know vector, I just wanted to try and figure it on my own but i guess im out of ideas...

anyways thanks.
closed account (E0p9LyTq)
Short answer: that is the C and C++ standard.

Here's how messy making an array run-time dynamic can be (one VERY simple example):

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>

int main()
{
   int* a = NULL;  // pointer to int, initialize to nothing.

   int n;          // size needed for array
   std::cin >> n;  // read in the size

   a = new int[n]; // allocate n ints and save ptr in a.

   for (int i = 0; i < n; i++)
   {
      a[i] = 3 * i + 1;    // initialize all elements to zero.
   }

   //. . . use a as a normal array
   for (int i = 0; i < n; i++)
   {
      std::cout << a[i] << "\t";
   }
   std::cout << std::endl;

   delete [] a;  // when done, free memory pointed to by a.
   a = nullptr;

   return 0;
}


Do you really want to deal with all those memory management details?
Do you really want to deal with all those memory management details?

hell, if i need to learn that then yes ;)
closed account (E0p9LyTq)
Better to learn the use of C++ containers first.

After getting a good solid foundation, then learning the details would be more productive.

Bjarne Stroustrup, the guy to created C++, in his book "Programming: Principles and Practices Using C++ (2nd Edition)" introduces vectors in the 4th chapter. He doesn't talk about arrays, as well as free store or heap memory, until chapter 17.

He introduces GUI programming in chapter 12!
Im reading now c++ Primer plus 6th edition recommended by friend.
Is this book ok?
closed account (E0p9LyTq)
"What books should I buy (or not buy)?

http://www.cplusplus.com/faq/beginners/books/

See also: https://isocpp.org/wiki/faq/how-to-learn-cpp#buy-several-books

Topic archived. No new replies allowed.