Accessing elements in a std::string with pointers - c++

How can I access individual elements in a std::string with pointers? Is it possible without type casting to a const char *?
#include <iostream>
#include <string>
using namespace std;
int main() {
// I'm trying to do this...
string str = "This is a string";
cout << str[2] << endl;
// ...but by doing this instead
string *p_str = &str;
cout << /* access 3rd element of str with p_str */ << endl;
return 0;
}

There are two ways:
Call the operator[] function explicitly:
std::cout << p_str->operator[](2) << '\n';
Or use the at function
std::cout << p_str->at(2) << '\n';
Both of these are almost equivalent.
Or dereference the pointer to get the object, and use normal indexing:
std::cout << (*p_str)[2] << '\n';
Either way, you need to dereference the pointer. Through the "arrow" operator -> or with the direct dereference operator * doesn't matter.

Related

g++: crash when accessing ostringstream::str().c_str()

The code below fails on gcc 9.4.0. Is this just a bug, or have I done something stupid?
log declares an ostringstream object, writes a filename and a line number to it, and attempts to do something with the object's underlying str().c_str().
Valgrind shows this crashing at the pointer access. The output I get is:
foo.cc, line 100
cptr is at 0x55c45e8f00c0, and is
#include <iostream>
#include <sstream>
#include <cstdarg>
using std::cout;
using std::ostringstream;
void log(const char *fname, int lineno) {
ostringstream outstr;
outstr << fname << ", line " << lineno;
cout << outstr.str() << '\n'; // prints Ok
const char *cptr = outstr.str().c_str();
cout << "cptr is at " << (void*) cptr << ", and is " << cptr; // crash
}
int main() {
log("foo.cc", 100);
}
std::ostringstream::str() returns a temporary string which will be destructed at the end of the line, this then means cptr is a dangling pointer.
Try:
std::string str = outstr.str();
const char *cptr = str.c_str();
cout << "cptr is at " << (void*) cptr << ", and is " << cptr;

try to understand the pointers maintained by a string object

Ran a simple program to test the pointer in string object, got
0x1875028
Hello
0x1875058 0x1875028
Hello world!!!
0x1875028
I am trying to understand why would s.c_str() change value after erase() call but not st.c_str().
Here is the simple code:
#include <vector>
#include <unordered_map>
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
string st;
void dum() {
string s("Hello world!!!");
printf("%p\n", s.c_str());
st = s;
s.erase(6);
cout << s << endl;
printf("%p %p\n", s.c_str(), st.c_str());
}
int main(int argc,char *argv[]) {
dum();
cout << st << endl;
st.erase(6);
printf("%p\n", st.c_str());
return 0;
}
This actually depends on the version you're using. See, for example Is std::string refcounted in GCC 4.x / C++11?. When you write for two strings, a, and b
a = b;
Then there's a question of whether they're internally pointing to the same object (up until one of them is modified). So either behavior your program exhibits is not very surprising.
First of all, I think this goes under the implementation details umbrella.
I tried that with VS2013.
After you call erase(), the string pointer returned by c_str() is not changed because I think the internal string implementation just updates the end of string (changing some internal data member), instead of doing a new heap reallocation for the internal string buffer (such an operation would likely return a new pointer value).
This is a behavior that I noted both for your local s string and the global st string.
Note that the STL implementation that comes with VS2013 doesn't use COW (COW seems to be non-standard C++11 compliant), so when you copy the strings with st = s, you are doing a deep copy, so the two strings are completely independent and they point to different memory buffers storing their respective string contents. So, when you erase something from one string, this operation is in no way reflected to the other copied string.
Sample Code
#include <iostream>
#include <string>
using namespace std;
// Helper function to print string's c_str() pointer using cout
inline const void * StringPtr(const string& str)
{
// We need a const void* to make cout print a pointer value;
// since const char* is interpreted as string.
//
// See for example:
// How to simulate printf's %p format when using std::cout?
// http://stackoverflow.com/q/5657123/1629821
//
return static_cast<const void *>(str.c_str());
}
string st;
void f() {
string s{"Hello world!!!"};
cout << "s.c_str() = " << StringPtr(s) << '\n';
st = s;
s.erase(6);
cout << s << '\n';
cout << "s.c_str() = " << StringPtr(s)
<< "; st.c_str() = " << StringPtr(st) << '\n';
}
int main() {
f();
cout << st << endl;
st.erase(6);
cout << "st.c_str() = " << StringPtr(st) << '\n';
}
Output
C:\Temp\CppTests>cl /EHsc /W4 /nologo test.cpp
test.cpp
C:\Temp\CppTests>test.exe
s.c_str() = 0036FE18
Hello
s.c_str() = 0036FE18; st.c_str() = 01009A40
Hello world!!!
st.c_str() = 01009A40

how to store the content of variable into const char*?

i have a pointer or variable which stores the address like 0xb72b218 now i have to store this value in to const char*. how i can store it. Thanks in advance.
I tried following:
suppose i have a pointer variable "ptr" which contains 0xb72b218 value
ostringstream oss;
oss << ptr;
string buf = oss.str();
const char* value = buf.c_str();
but it is more complicated any one know easy way.
Well... if you really want the address of something in a string, this will do:
#include <stdio.h>
#include <iostream>
int main(){
char buf[30];
void* ptr = /*your pointer here*/;
snprintf(buf,sizeof(buf),"%p",ptr);
std::cout << "pointer as string: " << buf << "\n";
std::cout << "pointer as value: " << ptr << "\n";
}
Or if you don't like magic numbers and want your code to work even when 256bit pointers are nothing special anymore, try this:
#include <limits> // for numeric_limits<T>
#include <stdint.h> // for intptr_t
#include <stdio.h> // for snprintf
#include <iostream>
int main(){
int i;
int* ptr = &i; // replace with your pointer
const int N = std::numeric_limits<intptr_t>::digits;
char buf[N+1]; // +1 for '\0' terminator
snprintf(buf,N,"%p",ptr);
std::cout << "pointer as string: " << buf << "\n";
std::cout << "pointer as value: " << static_cast<void*>(ptr) << "\n";
}
Example on Ideone.
OK, presumably there must some additional parameter that tells the function what type of data is actually being passed, but you can do it like this:
extern void afunc(const char *p, int type);
int value = 1234;
afunc((const char *)&value, TYPE_INT);
Have you looked at const_cast? It is a means of adding/removing const-ness from a variable in C++. Take a look here.

Error in using vector pointer in a function

I have this code, but it won't compile and i can't understand what is wrong - i guess the pointering of the vector is not correct.
My idea was to collect some numbers in main() and store them in a vector and array, and then pass the memory address of them to a function, and using a pointers to print the data stored.
I came up with this when i read something about pointers which said that i should use them in order to save memory, so IMO the code below will not copy the contents of the vector and the array but use a pointer to access their location in memory - that's what i want to do.
#include <iostream>
#include <vector>
using namespace std;
void function(vector<int>* a, int *s)
{
cout << "function starts.." << endl;
for(int i=0;i<a->size();i++)
{
cout << a[i] << endl;
cout << s[a[i]] << endl;
}
cout << "function ends..." << endl;
}
int main(void)
{
vector<int> m;
int s[102];
for(int i=0;i<10;i++)
{
m.push_back(i*i);
s[i*i] = i-2;
}
function(&m, &s);
return 0;
}
I receive several errors on compiling, something is wrong.
Please tell me what's wrong with my code and how to fix it. thank you...
You should pass the vector by reference, not by pointer:
void function(vector<int>& a, int *s)
And then
function(m, ...);
Using [] on a pointer to a vector would certainly cause strange problems because it behaves as if a pointed to an array of std::vectors (while it actually only points to one). The vectors itself are never indexed by that. You could also use (*a)[...] to index the vector by the pointer.
if you insist in parsing by pointer then the correct syntax shoulld be:
void function(vector<int>* a, int *s[])
{
cout << "function starts.." << endl;
for(int i=0;i<a->size();i++)
{
cout << (*a)[i] << endl;
cout << (*s)[(*a)[i]] << endl;
}
cout << "function ends..." << endl;
}
First of all in the main program s is a pointer to an int, while m is a vector. Thus the function call should be as follows:
function(&m, s);
Secondly in the function a is a pointer to a vector, so should be indexed as follows: (*a)[i].
However you should really be using const references to pass your vector around:
void function(const vector& a, int *s)
{
..
cout << a[i] << endl;
..
}
And call it like:
function(m, s);
(corrected)
&s is in fact int(*)[102]: pointer to a pointer to an array of 102 items.
You should just say
function(&m, s);
This is because by old C legacy rule, an array is essentially a const pointer to its item with index 0. So s is already int*
This version works:
#include <iostream>
#include <vector>
using namespace std;
void function(const vector<int>& a, int s [102])
{
cout << "function starts.." << endl;
for(int i=0;i<(int)a.size();i++)
{
cout << a [i] << endl;
cout << s[a [i]] << endl;
}
cout << "function ends..." << endl;
}
int main(void)
{
vector<int> m;
int s[102];
for(int i=0;i<10;i++)
{
m.push_back(i*i);
s[i*i] = i-2;
}
function(m, s);
return 0;
}

Optimizing sorting container of objects with heap-allocated buffers - how to avoid hard-copying buffers?

I was making sure I knew how to do the op= and copy constructor correctly in order to sort() properly, so I wrote up a test case. After getting it to work, I realized that the op= was hard-copying all the data_.
I figure if I wanted to sort a container with this structure (its elements have heap allocated char buffer arrays), it'd be faster to just swap the pointers around. Is there a way to do that? Would I have to write my own sort/swap function?
#include <deque>
//#include <string>
//#include <utility>
//#include <cstdlib>
#include <cstring>
#include <iostream>
#include <fstream>
#include <algorithm> // I use sort(), so why does this still compile when commented out?
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
using namespace std;
namespace fs = boost::filesystem;
class Page
{
public:
// constructor
Page(const char* path, const char* data, int size) :
path_(fs::path(path)),
size_(size),
rawdata_(new char[size])
{
// cout << "Creating Page..." << endl;
strncpy(rawdata_, data, size);
// cout << "done creating Page..." << endl;
}
// copy constructor
Page(const Page& other) :
path_(fs::path(other.path())),
size_(other.size()),
rawdata_(new char[other.size()])
{
// cout << "Copying Page..." << endl;
strncpy(data_, other.data(), size_);
// cout << "done copying Page..." << endl;
}
// destructor
~Page() { delete[] data_; }
// accessors
const fs::path& path() const { return path_; }
const char* data() const { return rawdata_; }
int size() const { return size_; }
// operators
Page& operator = (const Page& other) {
if (this == &other)
return *this;
char* newImage = new char[other.size()];
strncpy(newImage, other.data(), other.size());
delete[] data_;
rawdata_ = newImage;
path_ = fs::path(other.path());
size_ = other.size();
return *this;
}
bool operator < (const Page& other) const { return path_ < other.path(); }
private:
fs::path path_;
int size_;
char* rawdata_;
};
class Book
{
public:
Book(const char* path) :
path_(fs::path(path))
{
cout << "Creating Book..." << endl;
cout << "pushing back #1" << endl;
// below, the RawData will be coming from methods like
// fstream.read(char* buffer, int filesize); or
// unzReadCurrentFile(unzFile zipFile, char* buffer, int size);
pages_.push_back(Page("image1.jpg", "firstImageRawData", 17));
cout << "pushing back #3" << endl;
pages_.push_back(Page("image3.jpg", "thirdImageRawData", 17));
cout << "pushing back #2" << endl;
pages_.push_back(Page("image2.jpg", "secondImageRawData", 18));
cout << "testing operator <" << endl;
cout << pages_[0].path().string() << (pages_[0] < pages_[1]? " < " : " > ") << pages_[1].path().string() << endl;
cout << pages_[1].path().string() << (pages_[1] < pages_[2]? " < " : " > ") << pages_[2].path().string() << endl;
cout << pages_[0].path().string() << (pages_[0] < pages_[2]? " < " : " > ") << pages_[2].path().string() << endl;
cout << "sorting" << endl;
BOOST_FOREACH (Page p, pages_)
cout << p.path().string() << endl;
sort(pages_.begin(), pages_.end());
cout << "done sorting\n";
BOOST_FOREACH (Page p, pages_)
cout << p.path().string() << endl;
cout << "checking datas" << endl;
BOOST_FOREACH (Page p, pages_) {
char data[p.size() + 1];
strncpy((char*)&data, p.data(), p.size());
data[p.size()] = '\0';
cout << p.path().string() << " " << data << endl;
}
cout << "done Creating Book" << endl;
}
const Page& getFirstPage() { return pages_[0]; }
private:
deque<Page> pages_;
fs::path path_;
};
int main() {
Book* book = new Book("/some/path/");
// below is an example of where the rawdata is used
// by a method that has a char* parameter
ofstream outFile("outimage.jpg");
outFile.write(book->getFirstPage().data(), book->getFirstPage().size());
}
I wouldn't use raw char * in this scenario as it's going to be an unnecessary headache. Use std::string instead, which will remove the need for the copy constructor, assignment operator and destructor as the compiler-generated ones will be sufficient.
If you then find that copying the data is still a major bottleneck, you could use a boost::shared_ptr to hold the string if you can live with the additional level of indirection in normal use. That way, the string will not be copied if the containing object is copied and you still get the safety of RAII.
If using manual char* manipulation isn't part of your criteria for the exercise, you could use std::string and let it handle all the allocation issues for you. The std::swap function used by std::sort is even specialized to call std::string::swap for you, which means that it automatically only swaps the pointers to your string data rather than deep-copying.
If you want to use char* for exercise purposes, probably the easiest way to create a free-standing swap function that takes two Page references and just swaps the internal data pointers around. I believe that as long as sort can see a better match than the standard template, it will call your function instead getting the increased performance.
Finally, to answer your question about the header : Compilers are free to implement headers as actual files that include other headers (even ones that might not normally be expected). Almost certainly your iostream header is including algorithm directly or indirectly. On another compiler your code might fail to compile.