-3

Say I have a text file that has two integers like this:

3, 2

I do not understand pointers at all, so how would i read the text file so that it would multiply those two number and store it into an array of structs named

element* m1 = new element[size1]

this is just a small part of a much larger assignment that I am working on but I am stuck on this part.

  • Unless you are constrained to use arrays, prefer [`std::vector`](http://en.cppreference.com/w/cpp/container/vector). – R Sahu Feb 28 '18 at 04:37
  • Do you only have these two integers in the text file? Also, you haven't shared what the data structure element is like. – Zeokav Feb 28 '18 at 04:45
  • Don't let pointers stump you. A pointer is nothing but a variable that holds the address of something else as its value. You normally think of `int a = 5;` where `a` holds the immediate value `5` as its value. `int *b = &a;` creates the integer pointer `b` that simply holds the *address of* `a` as its value (e.g. `b` points to `a`). After a pointer is initialized, to get the thing it points to, you simply *dereference* the pointer using the `*` operator (e.g `printf ("the value at the address stored by 'b': %d\n", *b);`. That's pretty much the basics. – David C. Rankin Feb 28 '18 at 04:46
  • For your overall solution, you may find the first part of [CSV data into a 2D array of integers](https://stackoverflow.com/questions/48994605/csv-data-into-a-2d-array-of-integers/48996766#48996766) directly on point. (it is filling the intermediate row-vector `v` with comma separated values from a file -- you can omit the second `push_back` into `array`). – David C. Rankin Feb 28 '18 at 04:53

1 Answers1

1

If you do not understand pointers at all, don't dynamically allocate arrays yourself. Use a std::vector instead. It is basically a resizable array that handles the memory allocation and deallocation for you.

If you don't already have one, get a good book. There are a lot of bad C++ teaching out there, and a good example is teaching dynamic memory before vectors since dynamic memory and pointers are easy to misuse.

eesiraed
  • 4,626
  • 4
  • 16
  • 34
  • 2
    I get what you are saying, but there is quite a bit of dynamic allocation that goes on under the hood of `std::vector`. This is borderline needing to be a comment. – David C. Rankin Feb 28 '18 at 04:49
  • @DavidC.Rankin I meant to not do it yourself, but I'll edit it to make it more clear. – eesiraed Feb 28 '18 at 05:51