C++ 初始化无符号字符的正确方法*

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4875935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:49:32  来源:igfitidea点击:

Proper Way To Initialize Unsigned Char*

c++ccharunsigned

提问by Brian

What is the proper way to initialize unsigned char*? I am currently doing this:

初始化的正确方法是unsigned char*什么?我目前正在这样做:

unsigned char* tempBuffer;
tempBuffer = "";


Or should I be using memset(tempBuffer, 0, sizeof(tempBuffer));?

还是我应该使用memset(tempBuffer, 0, sizeof(tempBuffer));

采纳答案by Karl Bielefeldt

The second method will leave you with a null pointer. Note that you aren't declaring any space for a buffer here, you're declaring a pointerto a buffer that must be created elsewhere. If you initialize it to "", that will make the pointer point to a static buffer with exactly one byte—the null terminator. If you want a buffer you can write characters into later, use Fred's array suggestion or something like malloc.

第二种方法会给你一个空指针。请注意,这里没有为缓冲区声明任何空间,而是声明了一个指向必须在其他地方创建的缓冲区的指针。如果你将它初始化为"",这将使指针指向一个只有一个字节的静态缓冲区——空终止符。如果您想要一个可以稍后写入字符的缓冲区,请使用 Fred 的数组建议或类似malloc.

回答by Dmitry

To "properly" initialize a pointer (unsigned char *as in your example), you need to do just a simple

要“正确”初始化一个指针(unsigned char *如您的示例中所示),您只需要做一个简单的

unsigned char *tempBuffer = NULL;

If you want to initialize an array of unsigned chars, you can do either of following things:

如果要初始化unsigned chars数组,可以执行以下任一操作:

unsigned char *tempBuffer = new unsigned char[1024]();
// and do not forget to delete it later
delete[] tempBuffer;

or

或者

unsigned char tempBuffer[1024] = {};

I would also recommend to take a look at std::vector<unsigned char>, which you can initialize like this:

我还建议std::vector<unsigned char>您查看,您可以像这样初始化:

std::vector<unsigned char> tempBuffer(1024, 0);

回答by Kerri Brown

As it's a pointer, you either want to initialize it to NULL first like this:

因为它是一个指针,你要么想像这样先将它初始化为 NULL:

unsigned char* tempBuffer = NULL;
unsigned char* tempBuffer = 0;

or assign an address of a variable, like so:

或分配变量的地址,如下所示:

unsigned char c = 'c';

unsigned char* tempBuffer = &c;

EDIT: If you wish to assign a string, this can be done as follows:

编辑:如果您想分配一个字符串,可以按如下方式完成:

unsigned char myString [] = "This is my string";
unsigned char* tmpBuffer = &myString[0];

回答by Thomas Matthews

If you know the size of the buffer at compile time:

如果您在编译时知道缓冲区的大小:

unsigned char buffer[SIZE] = {0};

For dynamically allocated buffers (buffers allocated during run-time or on the heap):

对于动态分配的缓冲区(在运行时或堆上分配的缓冲区):

1.Prefer the newoperator:

1.首选new运营商:

unsigned char * buffer = 0;  // Pointer to a buffer, buffer not allocated.
buffer = new unsigned char [runtime_size];

2.Many solutions to "initialize" or fill with a simple value:

2.“初始化”或用简单值填充的许多解决方案:

std::fill(buffer, buffer + runtime_size, 0); // Prefer to use STL
memset(buffer, 0, runtime_size);
for (i = 0; i < runtime_size; ++i) *buffer++ = 0;  // Using a loop

3.The C language side provides allocation and initialization with one call.
However, the function does not call the object's constructors:

3.C语言端提供一键分配和初始化。
但是,该函数不会调用对象的构造函数:

buffer = calloc(runtime_size, sizeof(unsigned char))

Note that this also sets all bits in the buffer to zero; you don't get a choice in the initial value.

请注意,这也会将缓冲区中的所有位设置为零;您无法选择初始值。

回答by Oliver Charlesworth

It depends on what you want to achieve (e.g. do you ever want to modify the string). See e.g. http://c-faq.com/charstring/index.htmlfor more details.

这取决于您想要实现的目标(例如,您是否想修改字符串)。有关更多详细信息,请参见例如 http://c-faq.com/charstring/index.html

Note that if you declare a pointer to a string literal, it should be const, i.e.:

请注意,如果您声明一个指向字符串文字的指针,它应该是const,即:

const unsigned char *tempBuffer = "";

回答by CashCow

If the plan is for it to be a buffer and you want to move it later to point to something, then initialise it to NULL until it really points somewhere to which you want to write, not an empty string.

如果计划是将它作为缓冲区,并且您希望稍后将其移动以指向某个内容,则将其初始化为 NULL,直到它真正指向您想要写入的某个地方,而不是一个空字符串。

unsigned char * tempBuffer = NULL;
std::vector< unsigned char > realBuffer( 1024 );
tempBuffer = &realBuffer[0]; // now it really points to writable memory
memcpy( tempBuffer, someStuff, someSizeThatFits );

回答by Lundin

The answer depends on what you inted to use the unsigned char for. A char is nothingelse but a small integer, which is of size 8 bits on 99% of all implementations.

答案取决于您打算使用 unsigned char 的目的。char只不过是一个小整数,在 99% 的实现中都是 8 位大小。

C happens to have some string support that fits well with char, but that doesn't limit the usage of char to strings.

C 恰好有一些字符串支持,非常适合 char,但这并没有将 char 的使用限制为字符串。



The proper way to initialize a pointer depends on 1) its scope and 2) its intended use.

初始化指针的正确方法取决于 1)它的范围和 2)它的预期用途。

If the pointer is declared static, and/or declared at file scope, then ISO C/C++ guarantees that it is initialized to NULL. Programming style purists would still set it to NULL to keep their style consistent with local scope variables, but theoretically it is pointless to do so.

如果指针被声明为静态,和/或在文件范围内声明,则 ISO C/C++ 保证它被初始化为 NULL。编程风格纯粹主义者仍然会将其设置为 NULL 以保持他们的风格与局部范围变量一致,但理论上这样做是没有意义的。

As for what to initialize it to... set it to NULL. Don't set it to point at "", because that will allocate a static dummy byte containing a null termination, which will become a tiny little static memory leak as soon as the pointer is assigned to something else.

至于初始化为什么...设置为NULL。不要将它设置为指向“”,因为这将分配一个包含空终止的静态虚拟字节,一旦将指针分配给其他东西,它就会成为一个微小的静态内存泄漏。

One may question why you need to initialize it to anything at all in the first place. Just set it to something valid before using it. If you worry about using a pointer before giving it a valid value, you should get a proper static analyzer to find such simple bugs. Even most compilers will catch that bug and give you a warning.

有人可能会问,为什么首先需要将其初始化为任何内容。只需在使用前将其设置为有效的值即可。如果你担心在给它一个有效值之前使用一个指针,你应该得到一个合适的静态分析器来发现这样简单的错误。甚至大多数编译器都会捕捉到那个错误并给你一个警告。