0

Is it possible to initialize in dynamic way using pointers but just after the struct definition? Please at the example. I tried that but I get an exception when I try cout << a->val << endl;

#include "stdafx.h"
#include <iostream>

using namespace std;


struct A{
public:
    int val = 0;
    A(){}

}*a,b,c;

int _tmain(int argc, _TCHAR* argv[]){

    cout << a->val << endl;//EXCEPTION
    cout << b.val << endl;
    int x;
    cin >> x;
    return 0;
}
2
  • 1
    What are you trying to do? a is a null pointer, which is why dereferencing it with -> causes an exception. Commented Nov 12, 2013 at 23:22
  • Maybe. But maybe not. After all, it's undefined behavior. Commented Nov 12, 2013 at 23:54

2 Answers 2

2

Yes

struct A
{
  // ...

} *a { new A };

and somewhere suitable:

delete a;

Generally bare pointers are not recommended, you should avoid them and if you really need pointers try to use smart pointers such as std::unique_ptr and std::shared_ptr

Sign up to request clarification or add additional context in comments.

Comments

1

Your code

struct A{
public:
    int val = 0;
    A(){}
}*a,b,c;

defines the structure A and declares three global variables, a, b, c.

a is of type 'A*' - i.e. pointer to type A, b and c are instances of type A.

Global variables of simple, base types (e.g. ints, pointers, etc), default to 0.

The result is equivalent to this:

struct A{
public:
    int val = 0;
    A(){}
};
A* a = NULL;
A b;
A c;

When your code then tries to use a without assigning a value to it, it is dereferencing a NULL pointer and crashes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.