-2

I'm just getting started in C++, moving from higher level languages. For something I'm building, I'm allocating space, then figuring out what kind of object you have. It's rather like the below, but the below doesn't work - I expect to get back my 45, but am getting a memory location, I think. What did I mess up?

void *ptr;
int a = 45;
ptr = malloc(sizeof(int));
memcpy(ptr, &a, sizeof(int));
int *b;
b = (int*)ptr;
std::cout << &b;
Carbon
  • 3,828
  • 3
  • 24
  • 51
  • 2
    Your code is very Cish. You really should not have to get this low down in C++. Can you explain what you are actually trying to do? There should be a C++ way to do it. – NathanOliver Apr 26 '17 at 12:45
  • 2
    If you're learning C++, you'll be better off following a [good C++ book](http://stackoverflow.com/q/388242/1782465) instead of starting from C concepts. This code has very little to do with "proper" C++, it's C. – Angew is no longer proud of SO Apr 26 '17 at 12:45
  • 3
    You should be dereferencing `b`, but you're taking its address. – ForceBru Apr 26 '17 at 12:45
  • Oh right. Duh. Oops. Specifically, I'm doing some stuff with MPI, which is why this is kind of c-ish – Carbon Apr 26 '17 at 12:47

1 Answers1

1

As in the comments: change std::cout << &b; to std::cout << *b;

However, if you really need malloc, next might be easier:

int *ptr;
int a = 45;
ptr = static_cast<int*>(malloc(sizeof(int)));
*ptr = a;  // memcpy(ptr, &a, sizeof(int)); can be done, but is not necessary.
std::cout << *ptr;
free(ptr);

More C++ but not advised:

int ptr* = new int(a);
std::cout << *ptr;
delete ptr;

Simpler when the pointer has a clear scope, because you don't have to remember to clean up:

std::unique_ptr<int> ptr = std::make_unique(a);
std::cout << *ptr;

However, pointers to primitives have little use in C++, so it is best to avoid them entirely except when needed in some libraries.

stefaanv
  • 14,072
  • 2
  • 31
  • 53