-3

i am running this in vs code. its just taking input and then it terminates. the output is blank.

this is the output

///

PS D:\c++\string> cd "d:\c++\string" ; if ($?) { g++ chararray.cpp -o chararray } ; if ($?) { .\chararray }

uu uugg gg

///

heres the code.

#include <iostream>
using namespace std;
int main()
{
   
    char *u;
    cin.getline(u, 19);
    cout << "well " << u;
}
  • Your code is a little bit dangerous, with the cin some data getting overwritten, at a more or less random location in memory. – MiniMik Jul 21 '21 at 07:26
  • 5
    Where do you think `u` is pointing to? I'd suggest you to invest in a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Lukas-T Jul 21 '21 at 07:29

2 Answers2

1

The local buffer char *u; hasn't been initialized, it may cause a SEGV crash, since calling getline will lead to writing into the address stored in u, and it's a random value now.

It would be better to use the alternative std::getline and std::string as the target string type, then we read an arbitrary length of the string (We void buffer overflow and other kinds of memory issues):


#include <iostream>

int main() {
  std::string line;
  std::getline(std::cin, line);
  std::cout << "well " << line;
  return 0;
}
prehistoricpenguin
  • 6,130
  • 3
  • 25
  • 42
-1

A better way would be to do some allocation of mem before you store some data there.

#include <iostream>
using namespace std;
int main()
{

  char *u = new char[20];
  // char u[20] = { "\0" }; // with this you do not need to delete the mem
  cin.getline(u, 19);
  cout << "well " << u;

  delete [] u; // do not forget to free your heap memory

}

MiniMik
  • 268
  • 1
  • 10