简体   繁体   中英

Buffer size: N*sizeof(type) or sizeof(var)? C++

I am just starting with cpp and I've been following different examples to learn from them, and I see that buffer size is set in different ways, for example:

char buffer[255];
StringCchPrintf(buffer, sizeof(buffer), TEXT("%s"), X);

VS

char buffer[255];
StringCchPrintf(buffer, 255*sizeof(char), TEXT("%s"), X);

Which one is the correct way to use it?

I've seen this in other functions like InternetReadFile, ZeroMemory and MultiByteToWideChar.

Neither is correct.

You are using StringCchPrintf(), which operates on the count of characters, not bytes. sizeof(buffer) returns the size of buffer in bytes, as does 255*sizeof(char). 255*sizeof(char) also has the disadvantage that you are duplicating the size of the array in two places - if you change the size of buffer but forget in the call to StringCchPrintf, you have a bug.

This happens to work since sizeof(char) is always 1.

You are also specifying buffer as char, but use TEXT() around the string - compiling with UNICODE will cause a break.

Any of the following would be correct:

char buffer[255];
StringCchPrintf(buffer, ARRAYSIZE(buffer), "%s", X);

TCHAR buffer[255];
StringCchPrintf(buffer, ARRAYSIZE(buffer), TEXT("%s"), X);

char buffer[255];
StringCbPrintf(buffer, sizeof(buffer), "%s", X);

TCHAR buffer[255];
StringCbPrintf(buffer, sizeof(buffer), TEXT("%s"), X);

Given the above two variants, the first one is vastly better, since it does not repeat the "magic constant" 255. If you wanted the second variant to be competitive with first, you have to do it as

const size_t BUFFER_SIZE = 255;
char buffer[BUFFER_SIZE];
StringCchPrintf(buf, BUFFER_SIZE*sizeof(char), TEXT("%s"), X);

sizeof(buffer) will work for a statically allocated array but not for a dynamically allocated array:

char buffer[255];
cout << sizeof(buffer) << endl;   // prints 255
char *p = new char[255];
cout << sizeof(p) << endl;        // prints 8 (on a 64-bit machine)
delete[] p;
return 0;

With this in mind I would recommend always using N * sizeof(type) for the sake of consistency and to avoid subtle bugs.

You should use constants for the size, not integers like you did.

Per Microsoft, the correct form to calculate what you want is this:

sizeof array / sizeof array[0]

http://msdn.microsoft.com/en-us/library/4s7x1k91%28VS.71%29.aspx

Also, sizeof isn't perfect because in some instances it will return the size of the pointer and not the size of the array. The term SIZE OF is a little misleading in this case, because you have to ask yourself - what am I actually getting the SIZE OF ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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