I have a vector aVector. It starts at some memory address, let it be 0x00cff87f in this case.  I also have a double D.  Now, when the program accesses the D above, it accesses some other address, of course.  What I need is that when the program accesses D above, to be pointed to address 0x00cff87f, the start of that array, and take the first sizeof(double) bytes as a double.  I tried passing pointer to D to a function and switch it, but that just changed where that pointer was pointing at, once I exited the function, D remained unchanged.  Basically, I need some way to tell the program that four bytes of memory starting at 0x00cff87f are a double and that when I ask for a double named D to get me the number at that address.  I have an array in memory that needs to be decomposed to basic types, but instead of copying everything unnecessarily, I'd rather just tell the program where it already is.  How do I do that?  EDIT:  I have a vector of unsigned chars that I want to read into other types. Something that C# BinaryReader would do with MemoryStream. I don't know how to do it in c++. There are only fstreams, there isn't one that deals with (binary) files already in memory.
122420
I get a transmission over the network that's an array of chars/bytes. It contains a header and some data. I'd like to map the header onto a struct. Here's an example:  #pragma pack(1)  struct Header {     unsigned short bodyLength;     int msgID;     unsigned short someOtherValue;     unsigned short protocolVersion; };  int main() {     boost::array&lt;char, 128&gt; msgBuffer;     Header header;      for(int x = 0; x &lt; sizeof(Header); x++)         msgBuffer[x] = 0x01; // assign some values      memcpy(&amp;header, msgBuffer.data(), sizeof(Header));      system("PAUSE");          return 0; }   Will this always work assuming the structure never contains any variable length fields? Is there a platform independent / idiomatic way of doing this?  Note:  I have seen quite a few libraries on the internet that let you serialize/deserialize, but I get the impression that they can only deserialize something if it has ben previously serialized with the same library. Well, I have no control over the format of the transmission. I'm definitely going to get a byte/char array where all the values just follow upon each other.
15391
What's the C++ way of parsing a string (given as char *) into an int? Robust and clear error handling is a plus (instead of ).
11055
I have a situation where I need to process large (many GB's) amounts of data as such:   build a large string by appending many smaller (C char*) strings trim the string convert the string into a C++ const std::string for processing (read only) repeat   The data in each iteration are independent.  My question is, I'd like to minimise (if possible eliminate) heap allocated memory usage, as it at the moment is my largest performance problem.  Is there a way to convert a C string (char*) into a stl C++ string (std::string) without requiring std::string to internally alloc/copy the data?  Alternatively, could I use stringstreams or something similar to re-use a large buffer?  Edit: Thanks for the answers, for clarity, I think a revised question would be:  How can I build (via multiple appends) a stl C++ string efficiently. And if performing this action in a loop, where each loop is totally independant, how can I re-use thisallocated space.
62334
I have an array of values that is passed to my function from a different part of the program that I need to store for later processing.  Since I don't know how many times my function will be called before it is time to process the data, I need a dynamic storage structure, so I chose a std::vector.  I don't want to have to do the standard loop to push_back all the values individually, it would be nice if I could just copy it all using something similar to memcpy.
22097
I'm currently working on some logging code that supposed to - among other things - print information about the calling function. This should be relatively easy, standard C++ has a type_info class. This contains the name of the typeid'd class/function/etc. but it's mangled. It's not very useful. I.e. typeid(std::vector&lt;int&gt;).name() returns St6vectorIiSaIiEE.  Is there a way to produce something useful from this? Like std::vector&lt;int&gt; for the above example. If it only works for non-template classes, that's fine too.  The solution should work for gcc, but it would be better if I could port it. It's for logging so it's not so important that it can't be turned off, but it should be helpful for debugging.
36521
I want to examine the contents of a std::vector in GDB, how do I do it?  Let's say it's a std::vector&lt;int&gt; for the sake of simplicity.
45998
I want to open a file for reading, the C++ way. I need to be able to do it for:   text files, which would involve some sort of read line function. binary files, which would provide a way to read raw data into a char* buffer.
58577
I have this simple test: double h; ... // code that assigns h its initial value, used below ... if ((h&gt;0) &amp;&amp; (h&lt;1)){  //branch 1 -some computations } else{  //branch 2- no computations }  I listed my values as I got some really strange results and for example if: h=1 then the first branch is reached and I do not understand why since if h=1 I want branch2 to be computed. Am I getting confused by something so obvious?  Edit: This is how I compute and then use h: double* QSweep::findIntersection(edge_t edge1,edge_t edge2) {   point_t p1=myPoints_[edge1[0]]; point_t p2=myPoints_[edge1[1]]; point_t p3=myPoints_[edge2[0]]; point_t p4=myPoints_[edge2[1]];  double xD1,yD1,xD2,yD2,xD3,yD3,xP,yP,h,denom; double* pt=new double[3];          // calculate differences   xD1=p2[0]-p1[0];   xD2=p4[0]-p3[0];   yD1=p2[1]-p1[1];   yD2=p4[1]-p3[1];   xD3=p1[0]-p3[0];   yD3=p1[1]-p3[1];      xP=-yD1; yP=xD1; denom=xD2*(-yD1)+yD2*xD1; if (denom==0) {     return NULL; } else{ h=(xD3*(-yD1)+yD3*xD1)/denom; } std::cout&lt;&lt;&quot;h is&quot;&lt;&lt;h&lt;&lt;endl; if (h &lt; 1) std::cout&lt;&lt;&quot;no&quot;&lt;&lt;endl; else std::cout&lt;&lt;&quot;yes&quot;&lt;&lt;endl; if (h==1) {     return NULL; } else{ if ((h&gt;0)&amp;&amp;(h&lt;1)){     pt[0]=p3[0]+xD2*h;       pt[1]=p3[1]+yD2*h;     pt[2]=0.00; } else{     return NULL; } }   return pt;    }  Edit: Okay, so it is clear how I should reformulate the condition. From: double h; if (h==1){    //computations here }  To: double h; if (abs(h-1)&lt;tolerance){   //computations here }  When I use double numbers. But how do I reformulate this? double h; if (h&lt;1){    //computations here }
21008
I was wondering in C++ if I have an enum can I access the value at the second index?  For example I have  enum Test{hi, bye};   if I want 'hi', can I do something like Test[0], thanks.
34159
After parsing collada files I found out that we have to load two(or more) indices each pointing to say a vertex or normal etc. like this (&lt;p>3 0 2 0 0 0&lt;/p>)  Is there a way to load (and use)these indices to indices buffer(ELEMENT_ARRAY_BUFFER) like this (vnvnvn...) ; where v is vertex pointer, n is normal pointer from the above. with vertices loaded to VBO1 like (vvvv...) and in VBO2 like (nnnn...). So that we dont have to repeat the normals in VBO2.  VBO like (vnvnvn...) is also ok. (and not something like this ), I'm not trying to use multiple indices buffer. I'm trying to put all the given indices into one index buffer and use them alternately.  (If I wasnt clear i will try for more clarification.)
28889
Supposing to have something like this:  #include &lt;map&gt; int main(){     std::map&lt;int,int&gt; m;     m[1] = 2;     m[2] = 4;     return 0; }   I would like to be able to inspect the contents of the map running the program from gdb. If I try using the subscript operator I get:    (gdb) p m[1] Attempt to take address of value not located in memory.   Using the find method does not yield better results:  (gdb) p m.find(1) Cannot evaluate function -- may be inlined   Is there a way to accomplish this?
38175
For example: sizeof(char*) returns 4.  As does int*, long long*, everything that I've tried.  Are there any exceptions to this?
9623
In what segment (.BSS, .DATA, other) of an executable file are static variables stored so that they don't have name collision? For example:   foo.c:                         bar.c: static int foo = 1;            static int foo = 10; void fooTest() {               void barTest() {   static int bar = 2;            static int bar = 20;   foo++;                         foo++;   bar++;                         bar++;   printf("%d,%d", foo, bar);     printf("%d, %d", foo, bar); }                              }   If I compile both files and link it to a main that calls fooTest() and barTest repeatedly, the printf statements increment independently.  Makes sense since the foo and bar variables are local to the translation unit.  But where is the storage allocated?  To be clear, the assumption is that you have a toolchain that would output a file in ELF format.  Thus, I believe that there has to be some space reserved in the executable file for those static variables. For discussion purposes, lets assume we use the GCC toolchain.
7366
How do I read a file into a std::string, i.e., read the whole file at once?  Text or binary mode should be specified by the caller. The solution should be standard-compliant, portable and efficient. It should not needlessly copy the string's data, and it should avoid reallocations of memory while reading the string.  One way to do this would be to stat the filesize, resize the std::string and fread() into the std::string's const_cast&lt;char*&gt;()'ed data(). This requires the std::string's data to be contiguous which is not required by the standard, but it appears to be the case for all known implementations. What is worse, if the file is read in text mode, the std::string's size may not equal the file's size.  A fully correct, standard-compliant and portable solutions could be constructed using std::ifstream's rdbuf() into a std::ostringstream and from there into a std::string. However, this could copy the string data and/or needlessly reallocate memory.    Are all relevant standard library implementations smart enough to avoid all unnecessary overhead?  Is there another way to do it?  Did I miss some hidden Boost function that already provides the desired functionality?     void slurp(std::string&amp; data, bool is_binary)
37944
Is there a max length for an array in C++?  Is it a C++ limit or does it depend on my machine? Is it tweakable? Does it depend on the type the array is made of?  Can I break that limit somehow or do I have to search for a better way of storing information? And what should be the simplest way?  What I have to do is storing long long int on an array, I'm working in a Linux environment. My question is: what do I have to do if I need to store an array of N long long integers with N > 10 digits?  I need this because I'm writing some cryptographic algorithm (as for example the p-Pollard) for school, and hit this wall of integers and length of arrays representation.
106456
Do you have to pass delete the same pointer that was returned by new, or can you pass it a pointer to one of the classes base types?  For example:  class Base { public:     virtual ~Base();     ... };  class IFoo { public:     virtual ~IFoo() {}     virtual void DoSomething() = 0; };  class Bar : public Base, public IFoo { public:     virtual ~Bar();     void DoSomething();     ... };  Bar * pBar = new Bar; IFoo * pFoo = pBar; delete pFoo;   Of course this is greatly simplified.  What I really want to do is create a container full of boost::shared_ptr and pass it to some code that will remove it from the container when it is finished. This code will know nothing of the implementation of Bar or Base, and will rely on the implied delete operator in the shared_ptr destructor to do the right thing.  Can this possibly work? My intuition says no, since the pointers will not have the same address.  On the other hand, a dynamic_cast&lt;Bar*> should work, so somewhere the compiler is storing enough information to figure it out.  Thanks for the help, everybody who answered and commented. I already knew the importance of virtual destructors, as shown in my example; after seeing the answer I gave it a little thought, and realized the whole reason for a virtual destructor is this exact scenario. Thus it had to work. I was thrown by the absence of a visible means of converting the pointer back to the original. A little more thinking led me to believe there was an invisible means, and I theorized that the destructor was returning the true pointer for delete to release. Investigating the compiled code from Microsoft VC++ confirmed my suspicion when I saw this line in ~Base:  mov eax, DWORD PTR _this$[ebp]   Tracing the assembler revealed that this was the pointer being passed to the delete function. Mystery solved.  I've fixed the example to add the virtual destructor to IFoo, it was a simple oversight. Thanks again to everyone who pointed it out.
20515
This question was inspired by a similar question:   My question is a little different:  Is there any way to determine the size of a C++ array programmatically?  And if not, why?  Every function I've seen that takes an array also requires an integer parameter to give it the size.  But as the linked question pointed out, delete[] must know the size of the memory to be deallocated.  Consider this C++ code:  int* arr = new int[256]; printf("Size of arr: %d\n", sizeof(arr));   This prints "Size of arr: 4", which is just the size of the pointer.  It would be nice to have some function which prints 256, but I don't think one exists in C++.  (Again, part of the question is why it doesn't exist.)  Clarification: I know that if I declared the array on the stack instead of the heap (i.e. "int arr[256];") that the sizeof operator would return 1024 (array length * sizeof(int)).