0

I need help to understand the basics of struct when used as pointer and then using its elements via c++ commands like cin etc.

Please also let me know if you think initialization is wrong. The basic idea of this exercise is to make 'A' of certain Size as defined in Struct Array.

Please dont use malloc etc as i am aware of doing this via C.

Thank You !!!

struct Array{
    int *A;
    int Size;
    int Length;
};

int main()
{
    struct Array *arr;
    cout << "Enter the size of array " << endl;

    arr = new Array();
    cin >> arr->Size;

    cout << "Hello world!" << endl;
    return 0;
}
  • "Please dont use malloc etc as i... " well... Please dont use `new` etc as doing manual memory allocation is dangerous and error prone. No reason to allocate `arr` via `new`, and you should use `std::vector` instead – 463035818_is_not_an_ai Mar 12 '19 at 10:21
  • 2
    `cin >> &(arr.Size);` is very wrong. Have you used `cin` to input integers before? How did you do it then? – Some programmer dude Mar 12 '19 at 10:21
  • 1
    Also, what have your book or tutorial (or class) told you about accessing members of structures or classes when you have a pointer to the structure or class? Have you ever seen the "arrow" operator `->` before? Lastly, besides the use of `cin` and `>>`, how would this really differ from doing it in C? – Some programmer dude Mar 12 '19 at 10:22
  • simply putting the variable there – Mandeep Chaudhary Mar 12 '19 at 10:23
  • 1
    lol replacing this "&(arr.Size)" with "arr->Size" – Mandeep Chaudhary Mar 12 '19 at 10:25
  • @Someprogrammerdude lol thank you for the quick fix it was due to ide i am using i thought it will take care of it but my question is how do i make *A of that cerain size without using malloc – Mandeep Chaudhary Mar 12 '19 at 10:26
  • Unless this is for an assignment or exercise, you should't be using pointers at all, but use `std::vector` instead. If this is for an exercise or assignment about pointers and dynamic allocation, remember that there are two variants of `new`: The plain `new` to allocate single objects, and `new[]`. – Some programmer dude Mar 12 '19 at 10:28
  • @Someprogrammerdude thank you very much for the info. However, how on earth i alocate *A in struct a certain size on heap memory ? – Mandeep Chaudhary Mar 12 '19 at 10:31
  • Read your book or tutorial. It should tell you that. And if you don't have a book or tutorial to read, then [here's a list of good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282). – Some programmer dude Mar 12 '19 at 10:37

1 Answers1

-1

I’m not 100% sure I get your question, but you can allocate an array like this:

int main() {
    cout << "Enter the size of array " << endl;

    Array * arr = new Array();
    cin >> arr->Size;

    arr->A = new int[arr->Size];

    cout << "Hello world!" << endl;
    return 0;
}
idmean
  • 14,540
  • 9
  • 54
  • 83