I am to the point I am confusing myself but here is what I have. I have only recently started to familiarize myself with pointers more to a point I feel more comfortable using them, but I am getting an error about the buffer in strcpy_s() being too small.
Please no comments about me using char arrays instead of std::string, its for the HL2SDK which centers around char arrays (no idea why) so I just stick to the pattern.
void func_a()
{
char *szUserID = new char[64];
char *szInviterID = new char[64];
char *szGroupID = new char[64];
sprintf(szUserID, "%I64d", GetCommunityID(szUserSteamID));
sprintf(szInviterID, "%I64d", GetCommunityID(g_CvarSteamID.GetString()));
GetGroupCommunityID(1254745, &szGroupID); // Group Steam Community ID
}
void GetGroupCommunityID(int groupID, char **communityID)
{
int staticID = 1035827914;
int newGroupID = 29521408 + groupID;
char *buffer = new char[64];
snprintf(buffer, sizeof(buffer), "%d%d", staticID, newGroupID);
strcpy_s(*communityID, sizeof(*communityID), buffer);
delete buffer;
}
The problem is you are using sizeof which is a compile time construct to determine the runtime length of *communityID. This will essentially resolve down to sizeof(char*). What you want though is the number of bytes / chars available in *communityID. This information needs to be passed along with the value
GetGroupCommunityID(1254745, &szGroupID, sizeof(szGroupID));
void GetGroupCommunityID(int groupId, char** communityID, size_t length) {
...
strcpy_s(*communityID, length, buffer);
}
Also in this example a double pointer is unnecessary because you're not changing the pointer, just it's contents. A single pointer will do just fine for that
GetGroupCommunityID(1254745, szGroupID, sizeof(szGroupID));
void GetGroupCommunityID(int groupId, char* communityID, size_t length) {
...
strcpy_s(communityID, length, buffer);
}
If you are using constants values (char *szGroupID = new char[64]) why not declare a constant with the value 64 and use this value; by the way sizeof(szGroupID) is going to return 4 bytes too in a 32 bits compiler.
The second parameter to strcpy_s is the actual size (number of characters) of the buffer pointed to by the first parameter. sizeof(*communityID) only gives you the size of a char * pointer, typically 4 bytes on a 32-bit system. You need to pass in the actual size of *communityID to the GetGroupCommunityID function and pass this on to strcpy_s.
Related
I am trying to read in a cstring from a edit control box in MFC, then put it into a char array in a struct, but since I cannot do something like clientPacket->path = convertfuntion(a); I had to create another char array to store the string then store it element by element.
That felt like a bandait solution, is there a better way to approach this? I'd like to learn how to clean up the code.
CString stri;//Read text from edit control box and convert it to std::string
GetDlgItem(IDC_EDIT1)->GetWindowText(stri);
string a;
a = CT2A(stri);
char holder[256];
strcpy_s(holder,a.c_str());
int size = sizeof(holder);
struct packet {
char caseRadio;
char path[256];
};
packet* clientPacket = new packet;
for (int t = 0; t < size; t++) {
clientPacket->path[t] = holder[t] ;
}
EDIT:This is currently what I went with:
CString stri;//Read text from edit control box and convert it to std::string
GetDlgItem(IDC_EDIT1)->GetWindowText(stri);
string a = CT2A(stri);
struct packet {
char caseRadio;
char path[CONSTANT];//#define CONSTANT 256
};
packet* clientPacket = new packet;
a = a.substr(0, sizeof(clientPacket->path) - 1);
strcpy_s(clientPacket->path, a.c_str());
I got a problem where I got "1path" instead of "path", turns out it read in caseRadio='1', fixed it by reading out caseRadio first in the server
I don't see the need to create the intermediate 'holder' char array.
I think you can just directly do
strcpy(clientPacket->path, a.c_str());
You may want to do this:
a= a.substr(0, sizeof(clientPacket->path)-1);
before the strcpy to avoid buffer overrun depending on whether the edit text is size limited or not.
You can copy directly into a user-provided buffer when using the Windows API call GetWindowTextA. The following illustrates how to do this:
struct packet {
char caseRadio;
char path[512];
} p;
::GetWindowTextA(GetDlgItem(IDC_EDIT1)->GetSafeHwnd(), &p.path[0],
static_cast<int>(sizeof(p.path)));
This does an implicit character encoding conversion using the CP_ACP code page. This is not generally desirable, and you may wish to perform the conversion using a known character encoding (such as CP_UTF8).
Use the CString.GetBuffer function to get a pointer to the string. In your struct, store the path as a char* instead of a char array.
struct packet {
char caseRadio;
char* path;
};
packet* clientPacket = new packet;
clientPacket->path = stri.GetBuffer();
Like this, maybe? strncpy(clientPacket->path, CT2A(stri).c_str(), 255);.
Also, better make the 256 bytes a constant and use that name, just in case you change this in 10 years.
I have a byte array serialized from a stream char* Buf which points to an array of 64 bytes.
I wish to cast it into a function input parameter Foo(char[4][16] Buf) without copying each and every single bytes.
Any easy for doing so?
You can cast any buffer to any array you want:
void Foo(char(&buf)[4][16])
{
}
int main()
{
char* buf = new char[64];
Foo((char(&)[4][16])(buf));
delete[] buf;
return 0;
}
I found the answer in link given by Michael Chourdakis
*reinterpret_cast<char(*)[4][16]>(Buf)
why it's not possible to create an char array in this way?
int main()
{
int len;
cin>>len;
char input_str[len];
cin>>input_str;
cout<<input_str;
return 0;
}
You cannot use a static array without knowing the size of the array at runtime. Instead you can use a pointer and use either "malloc" or "new" to allocate memory for the array dynamically:
1) First check that the user has entered a valid int
2) Once you have a valid int to work with, you can use...
char *input_str = new char[len];
for C++ or if you have to stick with plain old C use ...
char *input_str = (char *)malloc(len * sizeof(char));
I transfer message trough a CAN protocol.
To do so, the CAN message needs data of uint8_t type. So I need to convert my char* to uint8_t. With my research on this site, I produce this code :
char* bufferSlidePressure = ui->canDataModifiableTableWidget->item(6,3)->text().toUtf8().data();//My char*
/* Conversion */
uint8_t slidePressure [8];
sscanf(bufferSlidePressure,"%c",
&slidePressure[0]);
As you may see, my char* must fit in sliderPressure[0].
My problem is that even if I have no error during compilation, the data in slidePressure are totally incorrect. Indeed, I test it with a char* = 0 and I 've got unknow characters ... So I think the problem must come from conversion.
My datas can be Bool, Uchar, Ushort and float.
Thanks for your help.
Is your string an integer? E.g. char* bufferSlidePressure = "123";?
If so, I would simply do:
uint8_t slidePressure = (uint8_t)atoi(bufferSlidePressure);
Or, if you need to put it in an array:
slidePressure[0] = (uint8_t)atoi(bufferSlidePressure);
Edit: Following your comment, if your data could be anything, I guess you would have to copy it into the buffer of the new data type. E.g. something like:
/* in case you'd expect a float*/
float slidePressure;
memcpy(&slidePressure, bufferSlidePressure, sizeof(float));
/* in case you'd expect a bool*/
bool isSlidePressure;
memcpy(&isSlidePressure, bufferSlidePressure, sizeof(bool));
/*same thing for uint8_t, etc */
/* in case you'd expect char buffer, just a byte to byte copy */
char * slidePressure = new char[ size ]; // or a stack buffer
memcpy(slidePressure, (const char*)bufferSlidePressure, size ); // no sizeof, since sizeof(char)=1
uint8_t is 8 bits of memory, and can store values from 0 to 255
char is probably 8 bits of memory
char * is probably 32 or 64 bits of memory containing the address of a different place in memory in which there is a char
First, make sure you don't try to put the memory address (the char *) into the uint8 - put what it points to in:
char from;
char * pfrom = &from;
uint8_t to;
to = *pfrom;
Then work out what you are really trying to do ... because this isn't quite making sense. For example, a float is probably 32 or 64 bits of memory. If you think there is a float somewhere in your char * data you have a lot of explaining to do before we can help :/
char * is a pointer, not a single character. It is possible that it points to the character you want.
uint8_t is unsigned but on most systems will be the same size as a char and you can simply cast the value.
You may need to manage the memory and lifetime of what your function returns. This could be done with vector< unsigned char> as the return type of your function rather than char *, especially if toUtf8() has to create the memory for the data.
Your question is totally ambiguous.
ui->canDataModifiableTableWidget->item(6,3)->text().toUtf8().data();
That is a lot of cascading calls. We have no idea what any of them do and whether they are yours or not. It looks dangerous.
More safe example in C++ way
char* bufferSlidePressure = "123";
std::string buffer(bufferSlidePressure);
std::stringstream stream;
stream << str;
int n = 0;
// convert to int
if (!(stream >> n)){
//could not convert
}
Also, if boost is availabe
int n = boost::lexical_cast<int>( str )
What is the proper way to initialize unsigned char*? I am currently doing this:
unsigned char* tempBuffer;
tempBuffer = "";
Or should I be using memset(tempBuffer, 0, sizeof(tempBuffer)); ?
To "properly" initialize a pointer (unsigned char * as in your example), you need to do just a simple
unsigned char *tempBuffer = NULL;
If you want to initialize an array of unsigned chars, you can do either of following things:
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> tempBuffer(1024, 0);
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 pointer to 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.
As it's a pointer, you either want to initialize it to NULL first like this:
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];
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 new operator:
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:
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:
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.
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.html for more details.
Note that if you declare a pointer to a string literal, it should be const, i.e.:
const unsigned char *tempBuffer = "";
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.
unsigned char * tempBuffer = NULL;
std::vector< unsigned char > realBuffer( 1024 );
tempBuffer = &realBuffer[0]; // now it really points to writable memory
memcpy( tempBuffer, someStuff, someSizeThatFits );
The answer depends on what you inted to use the unsigned char for. A char is nothing else but a small integer, which is of size 8 bits on 99% of all implementations.
C happens to have some string support that fits well with char, but that doesn't limit the usage of char to strings.
The proper way to initialize a pointer depends on 1) its scope and 2) its intended use.
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.
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.
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.