-4
char *one = new char[1024];
char one1[] = "hello";
one = hello;
cout << sizeof(one) << endl;

I really want the last line to output sizeof(one1) but I know as it stands it will output the size of the pointer which is 4 or 8. Is there a way to extract the sizeof() of the array from just the pointer to the first letter?

  • 1
    Again, one of the questions, asked hundreds.. thousands times. Even the related questions suggest similar "problems". – Kiril Kirov Jan 10 '14 at 11:35
  • 2
    If you want to use a string in C++, why not use [`std::string`](http://en.cppreference.com/w/cpp/string/basic_string)? – Some programmer dude Jan 10 '14 at 11:37
  • By the way, you also have a problem with leaking memory here. You allocate memory and make `one` point to it, but then overwrite the pointer and thereby loosing the original pointer so you can't `delete` that allocated memory. – Some programmer dude Jan 10 '14 at 11:38

3 Answers3

1

Is there a way to extract the sizeof() of the array from just the pointer to the first letter?

No.

Unfortunately, you have to keep track of this explicitly and maybe pass around the length as extra arguments to functions etc.

You have tagged your question "C++". In C++ we usually use std::vector, std::string or other container classes to keep track of this.

Magnus Hoff
  • 21,529
  • 9
  • 63
  • 82
0

There is no way to do this - maybe use a std::vector instead, or a std::string if you just need char's.

Roger Rowland
  • 25,885
  • 11
  • 72
  • 113
0

No.

That information is simply not available at run-time. A pointer is just a pointer, there is nowhere for the extra information (about the area being pointed at) to live.

unwind
  • 391,730
  • 64
  • 469
  • 606