Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to String conversion?

Tags:

delphi

I am allocating the memory with GetMem (1028 bytes length), so I have an allocated Pointer.

Then I am reading the content and I know that there is e.g. 1028 bytes read. how can I cast pointer, or convert it to a string?

Should I null terminate the content of the memory prior to conversion?

Thanks!

like image 243
John Avatar asked Aug 30 '11 13:08

John


People also ask

How do I convert a pointer to a string in C++?

Create a pointer variable with the name ptr , that points to a string variable, by using the asterisk sign * ( string* ptr ). Note that the type of the pointer has to match the type of the variable you're working with.

Can pointer be reassigned?

As you know, an address of an object in C++ can be stored either through a reference or through a pointer. Although it might appear that they represent similar concepts, one of the important differences is that you can reassign a pointer to point to a different address, but you cannot do this with a reference.

How to make array of char of a string in c++?

The c_str() and strcpy() function in C++ C++ c_str() function along with C++ String strcpy() function can be used to convert a string to char array easily. The c_str() method represents the sequence of characters in an array of string followed by a null character ('\0'). It returns a null pointer to the string.

How do you print the address of a pointer in C++?

How do I print the address stored in the pointer in C++? int *ptr = &var; printf("%p", ptr); That will print the address stored in ptr will be printed.


1 Answers

Use SetString. Pass it a string variable, your pointer, and the string length (1028). Delphi strings are implicitly null-terminated, so the function will add that automatically (even if your buffer already has null bytes in it).

Better yet, set the length of the string and read your data directly into it instead of using an intermediary buffer. If you must use an intermediary buffer, you may as well use one that's statically sized to 1028 bytes instead of complicating your program with dynamic memory management.

like image 126
Rob Kennedy Avatar answered Oct 04 '22 17:10

Rob Kennedy