-1

I want to know how to access a vector inside a structure as defined below

#include<vector>
#include<iostream>
#include<stdlib.h>

using namespace std;

struct Hello{
    vector<int>vec ;
};

struct Hello *h[1][1];

int main()
{
    struct Hello *v = (struct Hello *)malloc(sizeof(struct Hello));
    h[0][0]=v;
    0][0]->vec.push_back(13);
    //How to add 13 to vector vec?
    //It shows an error. But why?
    cout<<h[0][0]->vec.at(0)<<endl;
    return 0;
}
lokusking
  • 7,000
  • 13
  • 38
  • 51

2 Answers2

3

This is your problem:

struct Hello *v = (struct Hello *)malloc(sizeof(struct Hello));

(As an aside, struct is superfluous every time it was used in that line.)

It does allocate space for a Hello, but does not construct it.
And Hello has a non-trivial ctor because its member std::vector has one, thus omitting the call to the ctor is wrong.

Either use placement-new to in-place construct the Hello, or better yet allocate and construct in one go the C++ way:

Hello *v = new Hello;
// andd later deallocate
delete v;

Best, just avoid dynamic allocation altogether:

Hello h;

Member-access uses . or for pointers ->.

Deduplicator
  • 41,806
  • 6
  • 61
  • 104
1

That's not how you write code in C++.

First, as properly mentioned in the comments, do not use malloc ever. Use new if you need dynamic memory allocation. Otherwise you would have non-constructed objects, like you have already been told.

Second, do not use new when you do not have to. If you need dynamic memory allocation, most probably you want to manage this memory with a smart pointer, like std::unique_ptr. To construct a unique_ptr<T>, use std::make_unique<T>() function. Using make_unique will make you program leak-free and exception safe at zero cost. Using make_unique() will prevent some tricky situations with leaking due to exceptions and save you a couple of keystrokes when writing the code. At zero cost, of course. See GotW #89 Solution: Smart Pointers.

Third, most likely you don't even need dynamic memory allocation here. This is not Java, we love to allocate things on the stack. Remember that std::vector itself does dynamic memory allocation to store its buffer. And due to move semantics it can move this storage effective at runtime. There is no much sense to allocate vector itself in dynamic memory. See Why should C++ programmers minimize use of 'new'?

Do a search on each emphasized item for details.

Community
  • 1
  • 1
Mikhail
  • 18,155
  • 5
  • 56
  • 129