-1

Check out the below code

  char *str;
  gets(str); // or fgets
  puts(str);

its an example program in c++. Actually I feel its not a good way of coding because we did not assign a memory location to the char pointer str. The book says char array[10] has a limitation of length whereas char pointer str does not have a fixed length, we can input as many chars as possible. But I believe pointers can never be used without assigning a memory address to it, as I have learnt in C.

I think this must be the right way of doing it,

  char a[100];
  char *str=a;
  fgets(a,100,stdin);
  puts(a);

Kindly make me sure. Is it a good way of coding pointers without assigning a variables memory address to it? or what are the best ways to do it. Let me know what happens if we use pointers without assigning a memory address.Thanks.

niko
  • 9,285
  • 27
  • 84
  • 131

4 Answers4

4

Is it a good way of coding pointers without assigning a variables memory address to it?

No. Dereferencing an uninitialized pointer has undefined behavior - never, ever do it!

If you need a variable-length array, consider using std::string (for representing strings) or std::vector (for practically any data type) instead.

3
  1. Using pointers without initialization causes undefined behavior. It should not be used.

  2. And also, gets is deprecated, because it's not safe, use gets_s or fgets instead, as in your second example.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
1

Your second example is correct. Using an uninitialized pointer causes undefined behaviour.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
1

I've always got in some sort of odd behaviors when it came to use uninitialized pointers.

I'm a malloc-freak in C language. In fact using an explicit arrays of char have always led to some weird outputting.

Plus the static pointers are not meant to be returned out of a function. you really don't want to do that.

vdegenne
  • 12,272
  • 14
  • 80
  • 106