简体   繁体   English

初始化指向堆栈上指针的指针

[英]Initialize pointer to pointer on the stack

I'm a C newbie, and I'm trying to do the pointer/memory thing right... 我是C新手,我正在尝试做正确的指针/内存操作...

In my case, I'm using strtol and I need to pass a **char to hold one of several return values, but allocating heap space is way overkill. 就我而言,我使用的是strtol,我需要传递一个** char来保存几个返回值之一,但是分配堆空间实在是太过分了。 The cleanest correct (I hope) way I can find, of getting space on the stack for this, is: 我可以找到的最干净正确的方法(我希望)是在堆栈上腾出空间:

char *_ = NULL;
char **endptr = &_;
ret = strtol("not a number", endptr, 0);

I'm curious, is there a more succinct or idiomatic way to get this effect? 我很好奇,是否有更简洁或惯用的方式来获得这种效果? I feel dirty naming things I will never use... 命名我永远不会使用的东西时,我感到很脏。

EDIT: to clarify, I DO intend to use endptr, just not _ 编辑:澄清一下,我确实打算使用endptr,而不是_

strtol accepts NULL as the second argument. strtol接受NULL作为第二个参数。 See http://www.cplusplus.com/reference/cstdlib/strtol/ 参见http://www.cplusplus.com/reference/cstdlib/strtol/

So you can write your code like this: 因此,您可以这样编写代码:

ret = strtol("not a number", NULL, 0);

If it didn't accept NULL, you can avoid one line of code like this: 如果不接受NULL,则可以避免这样的一行代码:

char *unused;
ret = strtol("not a number", &unused, 0);

If you don't need endptr, you are allowed to pass a null pointer to strtol. 如果不需要endptr,则可以将null指针传递给strtol。 Otherwise I wouldn't worry about naming a variable you won't use. 否则,我不必担心命名您将不会使用的变量。 Although I don't think I'd name it _ as you have. 尽管我不认为我会像您一样命名_

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

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