Getting the address of a pointer and convert it in a wxString - c++

I'm trying to convert the address of a pointer to a wxString of the wxWidgets library.
I have this book that presents a console based example to explain the input/output stream system in C++. Here we can print the address of some pointers without much complications using
const char *const variable = "again";
cout << static_cast<void*>(variable);
So far I can understand the example but (Now the complication)I want to make some GUI off the examples to train myself and explore the wxWidgets classes along with the book. I've successfully made some conversions with the As() method of the wxAny class and even compiled it without warnings or errors. But in execution time I get an "Assert failure" when trying to convert the types.
If I let the program continue it prints in my wxTextCtrl things like:
ﻌњ̎X(
Any ideas??
(btw I use CodeBlocks with Mingw32 and wxWidgets 3.0 in a windows 7 system)
this is the code that gives me the assert failure:
void ConsoleFrame::OnbtnFrase2Click(wxCommandEvent& event)
{
string chaine2("Value of the pointer: ");
void* puntero = &chaine2;
wxAny anyThing= puntero;
consoleText->AppendText(anyThing.As<wxString>());
}
This is the method that gives me the assert failure error.
Thanks to #Grady for correcting the code before.
Seems that I cannot convert a void* to a wxString. I have a gist of what may the problem be but, I cannot find a solution to the original problem of printing the address of a pointer in a text control (NOT the console screen)

A common way to do what you want in C++ is using std::stringstream (you need to #include <sstream>). The body of your function would then look like this:
string chaine2("Value of the pointer: ");
void* puntero = &chaine2;
stringstream tmpss;
tmpss << chaine2 << puntero;
consoleText->AppendText(tmpss.str());
If you just want to get a wxString containing everything that was output to that stream, you just do something like:
wxString mystr = tmpss.str();

I don't know what your question has to do with wxWidgets, but this works for me:
const char * dog = "dog";
std::cout << &dog;
I am no C++ expert.. but to me that looks like "output address of variable dog"
and if you want that as a string you could use a C++ string stream or just happy old C sprintf
char * addrString = (char *)malloc(sizeof(void *) * 2 + 3); // *2 bytes for hex rep, +3 for "0x" and null
sprintf(addrString, "%p",dog);

There is a difference between the address of a pointer and the contents of the pointer, especially with C-style (nul terminated sequence of characters).
For example:
const char * const text = "Some Text\n";
The variable text is a pointer to a string literal. The contents of the pointer is the location where the string literal resides; often called an address.
The expression, &text, represents the location or the address of the pointer. So if the pointer is residing at address 0x4000, the expression &text would return 0x4000; not the content of the pointer.
There are examples on StackOverflow for printing the address of a variable and the contents or the C-Style string.
So, do you want a wxString containing the address of a pointer or the string literal that the pointer points to?

At last!!
The answer to my question was here:
http://docs.wxwidgets.org/trunk/classwx_text_ctrl.html
This is the documentation of the text control. I just had to REDIRECT the output stream to the text control with:
wxStreamToTextRedirector redirect(myTextControl);
And now I use the cout object normally,
cout<<puntero;
and the output will be presented in the text control instead of a console screen. I could not create the wxString containing the address but so far this can at least show it. I know that from here on I can create a string from the contents of the text control and the member functions of it. If any of you guys have a better answer, I will gladly accep it. It is funny how the chapter of the book where I am is in/out streams and the solution to my problem is not presented in the book.

Related

C++ String.h Char Tables cutting-off word without strstr

I need help with C++ <string.h> char tables.... How to cut word from sentence, using "*" operator, with no strstr? For example: "StackOverFlow is online website". I have to cut off "StackOverFlow" and leave in table "is online website" using operator, with no strstr. I couldn't find it anywhere.
Mostly like:
char t[]
int main
{
strcpy(t,"Stackoverflow is online website");
???
(Setting first char to NULL, then strcat/strcpy rest of sentence into table)
}
Sorry for English problems/Bad naming... I'm starting to learning C++
You can do something like this. Explain better what you need, please.
char szFirstStr[] = "StackOverflow, flowers and vine.";
strcpy(szFirstStr, szFirstStr + 15);
std::cout << szFirstStr << std::endl;
Will output "flowers and vine".
Using c strings is not good style for C++ programmer, use std::string class.
Your code is obviously syntactically incorrect, but I guess you are aware of that.
Your variable t is really a char array and you have a pointer that points to the first character of that char array, like you have a pointer that points to the first character of your null terminated string. What you can do is to change the pointer value to point to the new starting point of your string.
You can either do that, or if you indeed use an array, you can copy from the pointer of the new starting point you wish to use. So if the data you wish to copy resides in memory pointed to by:
const char* str = "Stackoverflow is an online website";
This looks like the following in memory:
Stackoverflow is an online website\0
str points to: --^
If you want to point to a different starting point you can alter the pointer to point at a different starting location:
Stackoverflow is an online website\0
str + 14 points to: --------------^
You can pass the address of the "i" to your strcpy, like so:
strcpy(t, str + 14);
Obviously it is not certain that you know the size to cut off without an analysis (the 14), what you might do is search through the string for the first character following a white space.
// Notice that this is just a sample of a search that could be made
// much more elegant, but I will leave that to you.
const char* FindSecondWord(const char* strToSearch) {
// Loop until the end of the string is reached or the first
// white space character
while (*strToSearch && !isspace(*strToSearch)) strToSearch++;
// Loop until the end of the string is reached or the first
// non white space character is found (our new starting point)
while (*strToSearch && isspace(*strToSearch)) strToSearch++;
return strToSearch;
}
strcpy(t, FindSecondWord("Stackoverflow is an online website"));
cout << t << endl;
This will output: is an online website
Since this is most likely a school assignment, I will skip the lecture on more modern C++ string handling, as I expect this has something to do with learning pointers. But obviously this is very low level modification of a string.
As a beginner why make it harder then it really have to be?
Use std::string
and
substr()
Link

Convert char* into String

I am using ESP8266 Wifi chip with the SMING framework which uses C++. I have a tcpServer function which receives data from a TCP port. I would like to convert the incoming char *data into String data type. This is what I did.
bool tcpServerClientReceive(TcpClient& client, char *data, int size)
{
String rx_data;
rx_data = String(data);
Serial.printf("rx_data=%s\r",rx_data);
}
The contents of rx_data is rubbish. What is wrong with the code? How to make rx_data into a proper string?
Why what you are doing is wrong:
A C style string is an array of char where the last element is a 0 Byte. This is how functions now where the string ends. They scan the next character until they find this zero byte. A C++ string is a class which can hold additional data.
For instance to get the length of a string one might choose to store the length of the stirng in a member of the class and update it everytime the string is modified. While this means additional work if the string is modified it makes the call t length trivial and fast, since it simply returns the stored value.
For C Strings on the other hand length has to loop over the array and count the number of characters until it finds the null byte. thus the runime of strlen depends on the lengh of the string.
The solution:
As pointed out above you have to print it correctly, try either:
#include <iostream>
...
std::cout << "rx_data=" << rx_data << std::endl;
or if you insist on printf (why use c++ then?) you can use either string::c_str(), or (since C++11, before the reutrned array might not be null terminated) string::data(): your code would become:
Serial.printf("rx_data=%s\r",rx_data.c_str());
I would suggest you have a look at std::string to get an idea of the details. In fact if you have the time a good book could help explaining a lot of important concepts, including containers, like std::string or std::vector. Don't assume that because you know C you know how to write C++.

Windows API and String concatenation [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 7 years ago.
I'm relatively new to C++ and the Windows API (coming from a Java background) and I was just playing around with the Windows API calling MessageBox and other simple functions until I tried to pass a concatenated string from a custom function to MessageBox where I noticed a weird output in the generated window.
This is the suspicious function:
const char* addFoo(const char* strInput)
{
return ("foo-" + std::string(strInput)).c_str();
}
It just returns the original input with a foo- added in front. (I hope I'm not doing anything incredibly wrong there)
In main I then do two calls to MessageBox first without calling the function but instead doing all the calculation on the fly, and afterwards calling the function:
const char* a = "bar";
MessageBox(NULL, ("foo-" + std::string(a)).c_str(), "The Foobar Experiment", MB_OK);
MessageBox(NULL, addFoo(a), "The Foobar Experiment", MB_OK);
This is the result I get by doing the string concatenation on the fly (case 1):
The result I get by calling the function addFoo (case 2):
Does anyone have any idea why I'm getting these unreadable characters on the generated window by using my addFoo function? Thanks in advance and sorry for the long post.
There are two fundamentally wrong things in your code, one being C++ related, the other being Windows related.
First, you are returning a pointer to a local entity, namely the return value of c_str() which is a pointer. Returning pointers to local variables is undefined behavior. What you want to do is return a string, not a pointer. In C++, there are string types such as std::string and std::wstring that implement the correct copy semantics that are required to have objects returned safely without error.
#include <string>
std::string addFoo(const char* strInput)
{
return "foo-" + std::string(strInput);
}
The second thing wrong with your code is that in the Windows world, you have basically two types of applications with respect to character type. You have the MBCS application, and Unicode application.
If you built a Unicode application, your calls to MessageBox would not have compiled successfully, since MessageBox takes wide character strings, not char based strings. In this case, the proper string type to use would be std::wstring.
You more than likely built an MBCS application, which in this day and age are becoming very rare.
const char* addFoo(const char* strInput)
{
return ("foo-" + std::string(strInput)).c_str();
}
This returns a pointer to a local temporary string, and its memory is released when your message box is shown.
Replace it by a std::string in your case:
std::string addFoo(const char* strInput)
{
return std::string("foo-") + strInput; // not sure about the syntax here
}
Then, std::string object manages its memory correctly and will make the string pointer remain alive for long enough for the message box to display it. You'll need to include <string> to get this defined.
Then, you can use:
std::string temp = addFoo( a );
MessageBox(NULL, temp.c_str(), "The Foobar Experiment", MB_OK);

Qt - C++ string concatenation segmentation fault

I'm new to c++, so I guess I fell into a newbyes C++ pitfall.
I tried to do the following:
QString sdkInstallationDirectory=getenv("somEnv");
QString someSourceDir=sdkInstallationDirectory+"\\Data\\"+someReference+ "\\src";
and I get a segmentation fault.
I guess this is because of the concatenation of the const chars and insufficient memory allocated to the someSourceDir QString.
What exactly is my mistake? How can I do this concatenation?
char * getenv ( const char * name );
A null-terminated string with the value of the requested environment
variable, or NULL if that environment variable does not exist.
Why you not check result?
EDIT.
So, check pointer is not necessary.
For historical reasons, QString distinguishes between a null string
and an empty string. A null string is a string that is initialized
using QString's default constructor or by passing (const char *)0 to
the constructor.
You can't add strings together with a +. Try using a stringstream.
Something like:
stringstream ss;
ss << sdkInstallationDirectory << "\Data\" + someReference << "\src";
string str = ss.str();
Although, if you are using Qt, you shouldn't be joining paths as strings.
See How to build a full path string (safely) from separate strings?
Thank you all for your answers.
It appears that I was wrong, and the segmentation fault was caused a line before, where I created the reference I mentioned in the question.
I discovered it with further debugging.
Sorry for the confusion, and thank you again!

How to concatenate const char* strings in c++ with no function calls?

Ps: This is more of a conceptual question.
I know this makes things more complicated for no good reason, but here is what I'm wondering. If I'm not mistaken, a const char* "like this" in c++ is pointing to l and will be automatically zero terminated on compile time. I believe it is creating a temporary variable const char* to hold it, unless it is keeping track of the offset using a byte variable (I didn't check the disassembly). My question is, how would you if even possible, add characters to this string without having to call functions or instantiating strings?
Example (This is wrong, just so you can visualize what I meant):
"Like thi" + 's';
The closest thing I came up with was to store it to a const char* with enough spaces and change the other characters.
Example:
char str[9];
strcpy(str, "Like thi")
str[8] = 's';
Clarification:
Down vote: This question does not show any research effort; it is unclear or not useful
Ok, so the question has been highly down voted. There wasn't much reasoning on which of these my question was lacking on, so I'll try to improve all of those qualities.
My question was more so I could have a better understanding of what goes on when you simply create a string "like this" without storing the address of that string in a const char* I also wanted to know if it was possible to concatenate/change the content of that string without using functions like strcat() and without using the overloaded operator + from the class string. I'm aware this is not exactly useful for dealing with strings in C++, but I was curious whether or not there was a way besides the standard ways for doing so.
string example = "Like thi" + "s"; //I'm aware of the string class and its member functions
const char* example2 = "Like this"; //I'm also aware of C-type Strings (CString as well)
It is also possible that not having English as my native language made things even worst, I apologize for the confusion.
Instead of using a plain char string, you should use the string library provided by the C++ library:
#include <string>
#include <iostream>
using namespace std;
int main()
{
string str = "Like thi";
cout << str << endl;
str = str + "s";
cout << str << endl;
return 0;
}
Normally, it's not possible to simply concatenate plain char * strings in C or C++, because they are merely pointers to arrays of characters. There's almost no reason you should be using a bare character array in C++ if you intend on doing any string manipulations within your own code.
Even if you need access to the C representation (e.g. for an external library) you can use string::c_str().
First, there is nothing null terminated, but the zero terminated. All char* strings in C end with '\0'.
When you in code do something like this:
char *name="Daniel";
compiler will generate a string that has a contents:
Daniel\0
and will initialize name pointer to point at it at a certain time during program execution depending on the variable context (member, static, ...).
Appending ANYTHING to the name won't work as you expect, since memory pointed to by name isn't changeable, and you'll probably get either access violation error or will overwrite something else.
Having
const char* copyOfTheName = name;
won't create a copy of the string in question, it will only have copyOfTheName point to the original string, so having
copyOfTheName[6]='A';
will be exactly as
name[6]='A';
and will only cause problems to you.
Use std::strcat instead. And please, do some investigating how the basic string operations work in C.