简体   繁体   English

使用指针而不为其分配变量存储地址

[英]Using a pointer without assigning a variable memory address to it

Check out the below code 看看下面的代码

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

its an example program in c++. 它是c ++中的示例程序。 Actually I feel its not a good way of coding because we did not assign a memory location to the char pointer str . 实际上,我觉得它不是一种很好的编码方式,因为我们没有将存储位置分配给char指针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. 该书说char array[10]有长度限制,而char pointer str没有固定长度,我们可以输入尽可能多的chars But I believe pointers can never be used without assigning a memory address to it, as I have learnt in C. 但是我相信,正如我在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. 让我知道如果我们使用指针而不分配内存地址会发生什么情况。

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. 如果需要变长数组,请考虑使用std::string (用于表示字符串)或std::vector (用于几乎任何数据类型)。

  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. 而且,不赞成使用gets ,因为它不安全,请改为使用gets_sfgets ,如第二个示例所示。

Your second example is correct. 您的第二个例子是正确的。 Using an uninitialized pointer causes undefined behaviour. 使用未初始化的指针会导致未定义的行为。

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. 我是C语言中的malloc怪胎 In fact using an explicit arrays of char have always led to some weird outputting. 实际上,使用显式的char数组总是导致一些奇怪的输出。

Plus the static pointers are not meant to be returned out of a function. 另外,静态指针并不意味着要从函数中返回。 you really don't want to do that. 你真的不想那样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM