question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
2,480,743 | 2,480,787 | Creating array with constant | I was working on a program in Netbeans on Linux using a gcc compiler when, upon switching to Visual C++ on Windows 7, the code failed to compile as Visual C++ says it expected constant expression on several lines. On Netbeans, I simply did something similar to char name[fullName.size()];, while on Visual C++, I tried, ... | In VC++ you can't do runtime declarations of stack array sizes, but you can do stack allocation via _alloca
so this:
const int position = fullName.size();
char Name[position];
becomes this:
const int position = fullName.size();
char * Name = (char*)_alloca(position * sizeof(char));
It's not quite the same thing, but ... |
2,480,894 | 2,484,149 | MFC/WIN32: mouse hover highlight in listctrl | The ListView control of Windows Explorer gives a highlight to whatever item is under the mouse, without affecting the current selection. This helps enormously with relating what item a given tooltip applies to within a listview - especially in report mode.
However, I am currently unable to find any APIs that would giv... | You can set the explorer theme to your list control. That way it will get a nicer look and you will also get the highlighting you want:
SetWindowTheme(hListControl, L"Explorer", NULL);
|
2,481,004 | 2,481,007 | Why aren't EXE's in binary? | Why is it that if you open up an EXE in a hex editor, you will see all sorts of things. If computers only understand binary then shouldn't there only be 2 possible symbols seen in the file? Thanks
| The hexadecimal values are interpreted binary values in memory. The software only make it a bit more readable to human beings.
0000 = 0
0001 = 1
0010 = 2
0011 = 3
0100 = 4
0101 = 5
0110 = 6
0111 = 7
1000 = 8
1001 = 9
1010 = 10 A
1011 = 11 B
1100 = 12 C
1101 = 13 D
1110 = 14 E
1111 = 15 F
|
2,481,142 | 2,481,163 | pointer to member function question | I'm trying to replicate a template I've used before with a member function, and it isn't going very well. The basic form of the function is
template<class T>
T Convert( HRESULT (*Foo)(T*))
{
T temp;
Foo(&temp); //Throw if HRESULT is a failure
return temp;
}
HRESULT Converter(UINT* val)
{
*val = 1;
... | TestClass is stateless. So why do you want to pass a non-static member function? If in the real code you need access to non-static members, you also need to pass the object along
template<class T, class C>
T Convert( HRESULT (C::*Foo)(T*), C c)
{
T temp;
(c.*Foo)(&temp); //Throw if HRESULT is a failure
retu... |
2,481,320 | 2,481,337 | What is the Best way to create a program which works only in the predefined trial period(evaluation period)? | I need to create a simple application that doesn't work after 30 days.
How can I do that ?
Is there a way to use Trial program after 30 days ?
| There is always a way to use a trial program after 30 days.
|
2,481,367 | 2,481,376 | How could one emulate namespace in C? | In C++ one might use namespace to keep independent groups working in the same code base from inadvertently creating functions with the same name and thus creating a conflict. My question is, before the idea of namespace comes out, how might one emulate namespace in C.
| By naming things differently, e.g.:
void namespace_group_function();
gtk+ is a prime example for this conventional style:
GtkWidget* gtk_window_new(GtkWindowType type);
|
2,481,535 | 2,481,547 | How to return a string literal from a function | I am always confused about return a string literal or a string from a function. I was told that there might be memory leak because you don't know when the memory will be deleted?
For example, in the code below, how to implement foo() so as to make the output of the code is "Hello World"?
void foo ( ) ... | I'm assuming we cannot modify main. To get your program working without a leak, you need something to have static storage:
void foo(char*& pC) // reference
{
static char theString[] = "thingadongdong";
pC = theString;
}
But really, this isn't very conventional C++ code. You'd be using std::string and std::co... |
2,481,632 | 2,508,356 | Why implement DB connection pointer object as a reference counting pointer? (C++) | At our company one of the core C++ classes (Database connection pointer) is implemented as a reference counting pointer. To be clear, the objects are NOT DB connections themselves, but pointers to a DB connection object.
The library is very old, and nobody who designed is around anymore.
So far, nether I, nor any C++ ... | Probably it's a mistake. Without looking at the code it's impossible to know for sure, but the quality of the reference-counted pointer implementation is suggestive. Poor design, especially around resource management, is not unheard of in the C++ community</bitter sarcasm>.
With that said, reference-counted pointers ... |
2,481,654 | 2,481,668 | memset for initialization in C++ | memset is sometimes used to initialize data in a constructor like the example below. Does it work in general ? Is it a good idea in general?
class A {
public:
A();
private:
int a;
float f;
char str[35];
long *lp;
};
A::A()
{
memset(this, 0, sizeof(*this));
}
| Don't use memset. It's a holdover from C and won't work on non-PODs. Specifically, using it on a derived class that contains any virtual functions -- or any class containing a non-builtin -- will result in disaster.
C++ provides a specific syntax for initialization:
class A {
public:
A();
private:
int a;
float... |
2,481,783 | 2,481,791 | What's the difference of pData1 and pData2, which are build as follows | What's the difference of pData1 and pData2, which are build as follows:
pData1 = (int*) calloc (i,sizeof(int));
int * pData2 = (int*) calloc (i,sizeof(int));
| Without any more information, it would appear the only difference is that pData2 is local to the allocation since it is declared as an int *. pData1 is not declared so it would have to have a larger (global?) scope and be defined elsewhere.
|
2,481,787 | 2,481,836 | Convert float to LPCWSTR/LPWSTR | [win 32 C++]
I don't know how to convert float to LPCWSTR/LPWSTR or LPCWSTR <-> LPWSTR
Thanks a lot
| #include <sstream>
...
float f = 45.56;
wstringstream wss;
wss << f;
// wss.str().c_str() returns LPCWSTR
cout << wss.str() << endl;
...
|
2,481,886 | 2,481,893 | Read/Write protected memory? | I'm trying to learn C++ currently, but I'm having issues with the code below.
class Vector2
{
public:
double X;
double Y;
Vector2(double X, double Y)
{
this->X = X;
this->Y = Y;
};
SDL_Rect * getSdlOffset()
{
SDL_Rect * offset = new SDL_Rect();
offset->x = t... | You never initialized X or Y... what do you those values might be? More than likely they are point to 00000X00(I am rusty this may not be the right address, but you are pointed to memory outside of your programs allocated space... thus the "GPF" I was C/C++ "convert" to Java(over 11 years ago) so I can appreciate your ... |
2,481,933 | 2,481,985 | Debugging strategy to find the cause of bad_alloc | I have a fairly serious bug in my program - occasional calls to new() throw a bad_alloc.
From the documentation I can find on bad_alloc, it seems to be thrown for these reasons:
When the computer runs out of memory (which definitely isn't happening, I have 4GB of RAM, program throws bad_alloc when using less than 5MB ... | Another possible problem is that, while you mention that the program is using less than 5MB, you don't mention how much space it's trying to allocate. You could have some race condition that's corrupting the value that you use to determine the allocation size, and it could be trying to allocate 37TB or somesuch nonsen... |
2,481,957 | 2,481,981 | How to find all the file handles by a process programmatically? | I have a process "x" which uses "system" C function to start ntpd daemon. I observed that ntpd are passed the open file descriptors of "x". ntpd holds on to the file descriptors even after original file is deleted. for ex: Some log files used by "x" are rotated out after sometime, but "ntpd" has file handle opened for... | Yes, it will cause a problem. The disk space used by the deleted files will not be released for reuse until the last open file descriptor is in fact closed.
Ideally, you would ensure that FD_CLOEXEC is set on all file descriptors; with POSIX 2008, you can do that when the file is opened with the O_CLOEXEC flag, even. ... |
2,481,998 | 2,482,077 | How do I include extremely long literals in C++ source? | I've got a bit of a problem. Essentially, I need to store a large list of whitelisted entries inside my program, and I'd like to include such a list directly -- I don't want to have to distribute other libraries and such, and I don't want to embed the strings into a Win32 resource, for a bunch of reasons I don't want t... | How about an array? (you would put the commas only after the legal limit for every element)
const std::wstring servicesWhitelist[] = {
L".NETFRAMEWORK|",
L"_IOMEGA_ACTIVE_DISK_SERVICE_|",
L"{6080A529-897E-4629-A488-ABA0C29B635E}|",
L"{834170A7-AF3B-4D34-A757-E05EB29EE96D}|",
L"{85CCB53B-23D8-4E73-B1B7-9DDB71827D9B... |
2,482,221 | 2,482,252 | Obtaining C++ Code Coverage |
I'm on Linux.
My code is written in C++.
My program is non-interactive; it runs as "./prog input-file", processes the file, and exits.
I have various unit tests "input-file0, input-file1, input-file2, ..."
For designing new unit tests, I want to know what lines of code existing tests do not cover.
Question: Given tha... | gcc comes with a code coverage testing tool (gcov):
http://gcc.gnu.org/onlinedocs/gcc/Gcov.html
|
2,482,257 | 2,482,395 | Need recommendation for object serialization library in c++ | I am looking for recommendation for object serialization/deserialization library in c++? Which one are the most advanced and open-sourced?
Can it handle
Any class that users defined?
Object hierarchy (parent and child classes)?
A Tree of objects? Class A has an attribute of Class B which has an attribute of Class C?... | It really depends what you're looking for. If you're looking for super-fast speed and rapid development within a library, Boost is awesome. If you're looking for super-fast speed, a little more customizability and cross-library binary compatibility, then Qt is a great solution (not saying that Boost can't be made to ... |
2,482,348 | 2,482,365 | Run C or C++ file as a script | So this is probably a long shot, but is there any way to run a C or C++ file as a script? I tried:
#!/usr/bin/gcc main.c -o main; ./main
int main(){ return 0; }
But it says:
./main.c:1:2: error: invalid preprocessing directive #!
| For C, you may have a look at tcc, the Tiny C Compiler. Running C code as a script is one of its possible uses.
|
2,482,435 | 2,482,443 | How to send message from one dialog to another? | I was given a task.
First dialog based application has 4
buttons (up, down, left, right).
Second dialog based application has
two controls (e.g. text area, button).
When on the first dialog I click
"left" button - controls on the second
dialog must move to the left.
But unfortunately I don't know Win32 A... | If you got handles (HWND) to the controls on the other dialog then you can use the Win32 MoveWindow api call to move them.
When reading the api documentation it might be useful to remember that everything (buttons, list boxes, combo boxes etc) is a window...
|
2,482,526 | 2,482,612 | Cleaning up a dynamic array of Objects in C++ | I'm a bit confused about handling an array of objects in C++, as I can't seem to find information about how they are passed around (reference or value) and how they are stored in an array.
I would expect an array of objects to be an array of pointers to that object type, but I haven't found this written anywhere. Would... | An array in C++ is an array of objects laid out in memory.
So for example in:
struct pair {
int x; int y;
};
...
pair array[10];
Each item in the array is going to be with a size of two ints.
If you want an array of pointers you can simply declare one:
pair* array_of_pointers[10];
The string objects have pointers ... |
2,482,564 | 2,482,604 | C++ Win32 Unhandled Exception Handler | currently I used SetUnhandledExceptionFilter() to provide callback to get information when an unhandled exception was occurred, that callback will provides me with EXCEPTION_RECORD which provides ExceptionAddress.
[1]what is actually ExceptionAddress is? does it the address of function / code that gives exception, or t... | (1) The ExceptionAddress is the address of the code that caused the exception. In case of an access violation error (0xC0000005) one of the additional arguments of the exception record holds the address from which a read or a write was attempted and another argument tells if it was a read or a write. This is documented... |
2,482,716 | 2,482,746 | Function in c++ for finding if a word is prefix | Let say i have some words AB, AAB, AA.
AB is not a prefix to AAB but AA is a prefix to AAB because if i just add B at the end of AA it will become AAB, which is not possible with AB.
So, is there any function in c++ (STL) so that i can determine of two words if one is prefix to the another ?
Thanks.
| template<class C, class T, class A>
bool starts_with(std::basic_string<C,T,A> const& haystack,
std::basic_string<C,T,A> const& needle)
{
return needle.length() <= haystack.length() &&
std::equal(needle.begin(), needle.end(), haystack.begin());
}
Note that the length check is not premature optimi... |
2,482,890 | 2,482,908 | How to create static method that evaluates local static variable once? | I have a class with static method which has a local static variable. I want that variable to be computed/evaluated once (the 1st time I call the function) and for any subsequent invocation, it is not evaluated anymore. How to do that? Here's my class:
template<
typename T1 = int, unsigned N1 = 1,
typename T2 = ... | Make another static function that does the computation, and use that for the initialization of the variable, e.g.
static uint32_t computeSize()
{
uint32_t init_totalSize;
// Lots of code
return init_totalSize;
}
static uint32_t getSize()
{
static uint32_t totalSize = computeSize();
return totalSize;
}
St... |
2,483,426 | 2,483,521 | Debugging metaprograms | Is there any way to check step by step what's going on in let's say template? I mean how it is instantiated step by step and so on?
In book I've mentioned here ,
I found (2 minutes ago) quite interesting example of how binary could be implemented as a metafunction.
template <unsigned long N>
struct binary
{
... | The best i've seen this far was the research paper on Templight, but i am not aware of any publicized implementation.
You can help yourself much though by using descriptive static (i.e. compile time) assertions - see e.g. Boosts static assert or MPLs asserts. In some cases it can help to provoke a compile error (e.g. b... |
2,483,491 | 2,483,937 | C++ Implicit Conversion Operators | I'm trying to find a nice inheritance solution in C++.
I have a Rectangle class and a Square class. The Square class can't publicly inherit from Rectangle, because it cannot completely fulfill the rectangle's requirements. For example, a Rectangle can have it's width and height each set separately, and this of course i... | Well, I'm surprised. It seems privately inheriting a class A prevents you from using operator A outside the class.
You can solve your problem by making a member Rectangle for square and using it for the cast:
class Square {
Rectangle r;
public:
operator const Rectangle&() const {
return r;
... |
2,483,577 | 2,483,603 | operator new and new operator, which can't be overloaded? | It seems both can be overloaded, but somebody said not.....
What's the case?
| It seems you are making the distinction between the handling of new-expressions and allocation functions. new-expressions call constructors in addition for class types and is responsible for looking up allocation functions (so it is built into the compiler) and calling them. You can't change that behavior. What you can... |
2,483,648 | 2,483,666 | C++ new line not translating | First off, I'm a complete beginner at C++.
I'm coding something using an API, and would like to pass text containing new lines to it, and have it print out the new lines at the other end.
If I hardcode whatever I want it to print out, like so
printInApp("Hello\nWorld");
it does come out as separate lines in the other ... | It is the compiler that process escape codes in string literals, not the runtime methods. This is why you can for example have "char c = '\n';" since the compiler just compiles it as "char c = 10".
If you want to process escape codes in strings such as '\' and 'n' as separate characters (eg read as such from a file), y... |
2,483,679 | 2,483,724 | When is "this" pointer initialized in C++? | Hi I have a question about this pointer, when an object is constructed, when it is initialized? Which means, when can I use it? The virtual table is constructed in the constructor, is the same with this pointer?
For example, I have a code like this. The output is 8. Does it mean that before the constructor is entered, ... | The this pointer isn't a member of the object or class - it's an implicit parameter to the method that you call. As such it's passed in much like any other parameter - except that you don't directly ask for it.
In your example above, the constructor is a special method, which is in turn a special kind of function. When... |
2,483,755 | 2,483,802 | How to programmatically gain root privileges? | I am writing some software (in C++, for Linux/Mac OSX) which runs as a non-privileged user but needs root privileges at some point (to create a new virtual device).
Running this program as root is not a option (mainly for security issues) and I need to know the identity (uid) of the "real" user.
Is there a way to mimic... | Original answer
You might consider the setuid switch on the executable itself. Wikipedia has an article on it which even shows you the difference between geteuid() and getuid() quite effectively, the former being for finding out who you're "emulating" and the latter for who you "are". The sudo process, for example, get... |
2,483,978 | 2,484,279 | Best way to implement globally scoped data | I'd like to make program-wide data in a C++ program, without running into pesky LNK2005 errors when all the source files #includes this "global variable repository" file.
I have 2 ways to do it in C++, and I'm asking which way is better.
The easiest way to do it in C# is just public static members.
C#:
public static cl... | If you absolutely have to have some global objects then the simplest way is to just to declare them extern in a header file included anywhere that needs access to them and define them in a single source file.
Your way #1 uses a class with only static members which means that it is essentially doing the job of a namespa... |
2,484,058 | 2,484,061 | How default assignment operator works in struct? | Suppose I have a structure in C++ containing a name and a number, e.g.
struct person {
char name[20];
int ssn;
};
Suppose I declare two person variables:
person a;
person b;
where a.name = "George", a.ssn = 1, and b.name = "Fred" and b.ssn = 2.
Suppose later in the code
a = b;
printf("%s %d\n",a.name, a.ssn);
| The default assignment operator does a member-wise recursive assignment of each member.
|
2,484,265 | 2,495,032 | How do I get rid of LD_LIBRARY_PATH at run-time? | I am building a C++ application that uses Intel's IPP library. This library is installed by default in /opt and requires you to set LD_LIBRARY_PATH both for compiling and for running your software (if you choose the shared library linking, which I did). I already modified my configure.ac/Makefile.am so that I do not ne... | As suggested by Richard Pennington, the missing library is not used directly by my application, but it is used by the shared libraries I use. Since I cannot recompile IPP, the solution to my problem is to add -liomp5 when compiling, using the -R option for the linker. This actually adds the rpath for libiomp5.so fixing... |
2,484,324 | 2,484,329 | C++ return double pointer from function.... what's wrong? | I can't seem to figure out what's wrong with my function.... I need to ask the user for a price and then return it as a double pointer, but I get tons and tons of errors:
double* getPrice()
{
double* price;
cout << "Enter Price of CD: " << endl;
cin >> &price;
return price;
}
| In order to use a pointer of any kind it needs to point to valid memory. Right now you have a pointer which is uninitialized and points to garbage. Try the following
double* price = new double();
Additionally you need to have cin pass to a double not a double**.
cin >> *price;
Note this will allocate new memory i... |
2,484,337 | 2,484,459 | Performance of std::pow - cache misses? | I've been trying to optimize a numeric program of mine, and have run into something of a mystery. I'm looping over code that performs thousands of floating point operations of which 1 call to pow - nevertheless, that call takes 5% of the time... That's not necessarily a critical issue, but it is odd, so I'd like to u... | If you replace std::pow(var) with another function, like std::max(var, var), does it still take up 5%? Do you still get all the cache misses?
I'm guessing no on time and yes on cache misses. Calculating powers is slower than many other operations (which are you using?). Calling out to code that's not in the cache wi... |
2,484,355 | 2,484,393 | STL Vectors, pointers and classes | Let's say i have 2 classes:
class Class1
{
public:
std::vector<CustomClass3*> mVec;
public:
Class1();
~Class1()
{
//iterate over all the members of the vector and delete the objects
}
};
class InitializerClass2
{
private:
Class1 * mPtrToClass1;
public:
InitializerClass2();
void Initialize()
{
... | In short this will work fine.
The memory being allocated in Initialize is on the heap. This means that changes in the stack do not affect the contents of this memory.
|
2,484,389 | 2,484,878 | Is it ok to pass *this in the constructor in the following example | Class A
{
A(B& b) : mb(b)
{
// I will not access anything from B here
}
B& mb;
};
Class B
{
B(): a(*this)
{}
A a;
}
I run into such a situation may times, the contained object needs to use the containers functionality. Having a reference to the container object in the contained object seems to be ... | The appropriate quote from the standard is:
§3.8 [basic.life]/6
Similarly, before the lifetime of an object has started but after the storage which the object will occupy has been allocated or, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any lvalue ... |
2,484,511 | 3,580,205 | Can I use Visual Studio 2010's C++ compiler with Visual Studio 2008's C++ Runtime Library? | I have an application that needs to operate on Windows 2000. I'd also like to use Visual Studio 2010 (mainly because of the change in the definition of the auto keyword). However, I'm in a bit of a bind because I need the app to be able to operate on older OS's, namely:
Windows 2000
Windows XP RTM
Windows XP SP1
Visu... | Suma's solution looked pretty promising, but it doesn't work: the __imp__*@4 symbols need to be pointers to functions, rather than the functions themselves. Unfortunately, I don't know how to make Visual C++ spit out a pointer with that kind of name generation... (well, __declspec(naked) combined with __stdcall does th... |
2,484,570 | 2,484,607 | Help understanding linux/tcp.h | I'm learning to use raw sockets, and im trying to prase out the tcp header data, but i can't seem to figure out what res1, ece, and cwr are. Through my networking book and google i know what the rest stand for, but can't seem to find anything on those three.
Below is the tcphdr struct in my includes area. Ive comment... | See http://en.wikipedia.org/wiki/Transmission_Control_Protocol#TCP_segment_structure
res1 is called reserved there. The others have the same name.
CWR (1 bit) – Congestion Window Reduced (CWR)
ECE (1 bit) – ECN-Echo indicates
|
2,484,606 | 2,484,756 | c++ library for endian-aware reading of raw file stream metadata? | I've got raw data streams from image files, like:
vector<char> rawData(fileSize);
ifstream inFile("image.jpg");
inFile.read(&rawData[0]);
I want to parse the headers of different image formats for height and width. Is there a portable library that can can read ints, longs, shorts, etc. from the buffer/stream, converti... | It's not that hard to do yourself. Here's how you can read a little endian 32 bit number:
unsigned char buffer[4];
inFile.read(buffer, sizeof(buffer));
unsigned int number = buffer[0] +
(buffer[1] << 8) +
(buffer[2] << 16) +
(buffer[3] << 24);
and to ... |
2,484,669 | 2,484,702 | Returning a dynamically created array from function | I'm trying to create a function that would dynamically allocate an array, sets the values of the elements, and returns the size of the array. The array variable is a pointer that is declared outside the function and passed as a parameter. Here is the code:
#include <cstdlib>
#include <iostream>
using namespace st... | You're passing in the array pointer by value; this means that when your doArray function returns, the value in arr in main is still NULL - the assignment inside doArray doesn't change it.
If you want to change the value of arr (which is an int *), you need to pass in either a pointer or a reference to it; hence, your ... |
2,484,766 | 2,484,788 | When to put C++ function in header file | I've been looking at Boost and various other C++ libraries. The vast majority of Boost is implemented in header files.
My question is: under what conditions do you do a header-only implementation (like Boost) or also include a .cpp file?
| If you want to use a template in another translation unit (i.e. another source file), you should (almost always) define it in the header file. (There are exceptions, like the comments below point out, but IMHO this is a good rule of thumb.)
Same applies if you want to use an inline function from another translation uni... |
2,484,829 | 2,487,316 | How to redraw the picture while moving windows in openGL? | I have drawn a picture with openGL on my windows. Now whenever I hold the mouse button on the windows and move it, my picture always got distorted. I don't know what function in openGL that can help me redraw the picture while the windows is moved. Anybody could help?
I tried this but seems not work:
void myDisplay()
{... | The first (and usually only) necessary step is to to quit using glut. glut is oriented primarily toward producing a static display, so it attempts to accumulate changes and then redraw only when the state has "stabilized" again, such as when you're done resizing the window. That made sense at one time, but mostly doesn... |
2,484,959 | 2,485,010 | Can you force a crash if a write occurs to a given memory location with finer than page granularity? | I'm writing a program that for performance reasons uses shared memory (sockets and pipes as alternatives have been evaluated, and they are not fast enough for my task, generally speaking any IPC method that involves copies is too slow). In the shared memory region I am writing many structs of a fixed size. There is one... | I don't think its possible to make a few bits read only like that at the OS level.
One thing that occurred to me just now is that you could put the reference counts in a different page like you suggested. If the structs are a common size, and are all in sequential memory locations you could use pointer arithmetic to lo... |
2,484,980 | 2,485,177 | Why is volatile not considered useful in multithreaded C or C++ programming? | As demonstrated in this answer I recently posted, I seem to be confused about the utility (or lack thereof) of volatile in multi-threaded programming contexts.
My understanding is this: any time a variable may be changed outside the flow of control of a piece of code accessing it, that variable should be declared to be... | The problem with volatile in a multithreaded context is that it doesn't provide all the guarantees we need. It does have a few properties we need, but not all of them, so we can't rely on volatile alone.
However, the primitives we'd have to use for the remaining properties also provide the ones that volatile does, so i... |
2,485,030 | 2,485,040 | deleting HBITMAP causes an access violation at runtime | I have the following code to take a screenshot of a window, and get the colour of a specific pixel in it:
void ProcessScreenshot(HWND hwnd){
HDC WinDC;
HDC CopyDC;
HBITMAP hBitmap;
RECT rt;
GetClientRect (hwnd, &rt);
WinDC = GetDC (hwnd);
CopyDC = CreateCompatibleDC (WinDC);
//Create a bitmap compatible with the DC
... | You must destroy GDI objects with DeleteObject, not delete. The latter is only used to free objects allocated using new.
|
2,485,057 | 2,485,109 | Pipe multiple files (gz) into C program | I've written a C program that works when I pipe data into my program using stdin like:
gunzip -c IN.gz|./a.out
If I want to run my program on a list of files I can do something like:
for i `cat list.txt`
do
gunzip -c $i |./a.out
done
But this will start my program 'number of files' times.
I'm interested in piping a... | There is no need for a shell loop:
gzip -cd $(<list.txt) | ./a.out
With the '-cd' option, gzip will uncompress a list of files to standard output (or you can use 'gunzip -c'). The $(<file) notation expands the contents of the named file as a list of arguments without launching a sub-process. It is equivalent to $(ca... |
2,485,058 | 2,485,117 | Equivalent to window.setTimeout() for C++ | In javascript there's this sweet, sweet function window.setTimeout( func, 1000 ) ; which will asynchronously invoke func after 1000 ms.
I want to do something similar in C++ (without multithreading), so I put together a sample loop like:
#include <stdio.h>
struct Callback
{
// The _time_ this functi... | Make Callback::func of type void (*)(), i.e.
struct Callback
{
double execTime;
void (*func)();
};
You can call the function this way:
c1.func();
Also, don't busy-wait. Use ualarm on Linux or CreateWaitableTimer on Windows.
|
2,485,120 | 2,485,131 | C++ cin problems. not capturing input from user | I have the following method which is not capturing anything from the user.If I input New Band for the artist name, it only captures "New" and it lefts out "Band". If I use cin.getline() instead nothing is captured. Any ideas how to fix this?
char* artist = new char [256];
char * getArtist()
{
cout << "Enter Artist... | std::string getArtist() {
using namespace std;
while (true) {
cout << "Enter Artist of CD: " << endl;
string artist;
if (getline(cin, artist)) { // <-- pay attention to this line
if (artist.empty()) { // if desired
cout << "try again\n";
continue;
}
cout << ... |
2,485,190 | 2,485,202 | How to edit the first line in a text file in c++? | I have a text file looks like this :
100 50 20 90
4.07498 0.074984
37.1704 28.1704
20.3999 14.3999
48.627 35.627 ....
I need to edit this file so that everything is kept the same except the first line, 3rd item. The ouput should look like this:
100 50 19 90
4.07498 0.074984
37.1704 28.1704
20.3999 14.3999
48.627 35.62... | #include <stdio.h>
int main()
{
FILE *pFile;
pFile = fopen("example.txt", "r+");
fseek(pFile, 7, SEEK_SET);
fputs("19", pFile);
fclose(pFile);
return 0;
}
Edit: The above was of course mostly a joke. The real way to do it is to read the first line, split it into parts, change the r... |
2,485,284 | 2,485,297 | getline(cin, variable) not wanting to work properly in c++? | Here's my program so far:
int main()
{
char choice = 'D';
string inputString;
cout << "Please input a string." << endl;
getline(cin, inputString);
LetterCount letterCount(inputString);
while(choice != 'E')
{
cout << "Please choose from the following: " << endl
<< "A) ... | i think you have to add something like this:
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
after your cin >> choice
The reason for this is, that the user actually entered 'D\n' but only 'D' fits into the choice variable, so the '\n' goes into the buffer of cin.
when you call getline, getline sees t... |
2,485,336 | 2,487,756 | Address of function is not actual code address | Debugging some code in Visual Studio 2008 (C++), I noticed that the address in my function pointer variable is not the actual address of the function itself. This is an extern "C" function.
int main() {
void (*printaddr)(const char *) = &print; // debug shows printaddr == 0x013C1429
}
Address: 0x013C4F10
void prin... | That is caused by 'Incremental Linking'. If you disable that in your compiler/linker settings the jumps will go away.
http://msdn.microsoft.com/en-us/library/4khtbfyf(VS.80).aspx
|
2,485,388 | 2,485,412 | Heuristic to identify if a series of 4 bytes chunks of data are integers or floats | What's the best heuristic I can use to identify whether a chunk of X 4-bytes are integers or floats? A human can do this easily, but I wanted to do it programmatically.
I realize that since every combination of bits will result in a valid integer and (almost?) all of them will also result in a valid float, there is no ... | You are going to be looking at the upper 8 or 9 bits. That's where the sign and mantissa of a floating point value are. Values of 0x00 0x80 and 0xFF here are pretty uncommon for valid float data.
In particular if the upper 9 bits are all 0 then this likely to be a valid floating point value only if all 32 bits are 0... |
2,485,495 | 2,485,515 | Are there any Netbooks powerful enough for moderate C++ compilation? | I've tried a few Asus Ones, and found that even switching between multiple windows could take seconds. Is there anything powerful enough in that form factor for C++ programmers to build small to moderate size projects?
| I also give it a qualified yes.
What OS you use may matter a lot. I have Kubuntu on a HP 2140 netbook with only 1 gb of ram and the usual Asus N270 cpu. And it is actually rather snappy for window or desktop switches etc under KDE 4.3.
Compile-times are ok but I am spoiled by better machines at the office or even at ho... |
2,485,503 | 2,492,162 | Embedding cg shaders in C++ GPGPU library | I'm writing a GPGPU Fluid simulation, which runs using C++/OpenGL/Cg. At the moment, the library requires that the user specify a path to the shaders, which is will then read it from.
I'm finding it extremely annoying to have to specify that in my own projects and testing, so I want to make the shader contents linked ... | You mean you want the shaders embedded as strings in your binary? I'm not aware of any cross-platform tools/libraries to do that, which isn't that surprising because the binaries will be different formats.
For Windows it sounds like you want to store them as a string resource. You can then read the string using LoadStr... |
2,485,565 | 2,485,570 | C++ print value of a pointer | I have an array of double pointers, but every time I try do print one of the values the address gets printed. How do I print the actual value?
cout << arr[i] ? cout << &arr[i] ? they both print the address
Does anyone know?
| If it's really an array of (initialized) double pointers, i.e.:
double *arr[] = ...
// Initialize individual values
all you need is:
cout << *arr[i];
|
2,485,614 | 2,485,626 | going reverse in a for loop? | Basically i got this for loop and i want the number inputed (eg. 123) to be printed out in reverse, so "321".
so far it works fine and prints out the correct order when the for loop is
for(i = 0; i<len ; i++)
but i get an error when i try to print it in reverse?. Whats going wrong?
#include <stdio.h>
#include <string... | Look at your for loop again:
for(i = len; i>len ; i--){
You're doing i=len, and then testing for i>len -- unless something goes seriously wrong in the assignment, that's never going to be true...
By the way, though it's not related, you shouldn't be using gets, even in a program like this that you never intend to put ... |
2,485,869 | 2,486,238 | How to read registry correctly for multiple values in c? | I created a .dll which should work like the RunAs command. The only difference is, that it should read from registry. My problem is, that i need to reed 3 values from the registry, but i can't. It reads the first, than it fails at the second one (Password) with error code 2, which means "The system cannot find the file... | I think I can see why. You need to initialize dwBufSize each time before you call RegQueryValueEx. This function returns the number bytes copied to buf.
You will find the function returns ERROR_MORE_DATA. You've made the mistake of using GetLastError(). Don't do that. The Reg functions return an error code directly.
|
2,485,899 | 2,485,909 | C++ sort array of char pointers | Can you tell me what's wrong with my method? I ends up putting the same thing everywhre and it's actually not sorting.
void sortArrays(){
int i, j;
for(i=0; i<counter; i++){
for( j=0; j<i; j++){
if( strcmp(title_arr[i], title_arr[j]) < 0){
char* title_temp = title_ar... | This:
char* title_temp = title_arr[i];
title_arr[j] = title_temp;
Is equivalent to:
title_arr[j] = title_arr[i];
You never swap them, you just copy one to the other. You should add this line:
title_arr[i] = title_arr[j];
In between the two. That way, you'll overwrite [i] with [j], but _temp still holds the old valu... |
2,485,977 | 2,485,983 | Operator overloading in C++ | If you overload - like operator-(), it is to be used to the left of the object, however overloading () like operator()() it is used to the right of the object. How do we know which operator is to be used on the left and which ones to be used on the right?
| Look at the operator precedence chart. This will tell you the direction the operator associates (binds). Note that some operators have multiple forms with different meanings, such as binary and unary -. In such cases, you may have multiple overloads, e.g.:
T operator-()
and:
T operator-(const T &o)
The compiler ch... |
2,486,034 | 2,486,055 | delete[] an array of objects | I have allocated and array of Objects
Objects *array = new Objects[N];
How should I delete this array?
Just
delete[] array;
or with iterating over the array's elements?
for(int i=0;i<N;i++)
delete array[i];
delete[];
Thanks
UPDATE:
I changed loop body as
delete &array[i];
to force the code to compile.
| Every use of new should be balanced by a delete, and every use of new[] should be balanced by delete[].
for(int i=0;i<N;i++)
delete array[i];
delete[] array;
That would be appropriate only if you initialized the array as:
Objects **array = new Objects*[N];
for (int i = 0; i < N; i++) {
array[i] = new Object;
... |
2,486,060 | 2,488,290 | Tips on how to deploy C++ code to work every where | I'm not talking about making portable code. This is more a question of distribution. I have a medium-sized project. It has several dependencies on common libraries (eg openssl, zlib, etc). It compiles fine on my machine and now it's time to give it to the world.
Essentially build engineering at its finest. I want ... | I would recommend CMake. Advantages:
It is very easy to use for building simple and complex projects with static libraries, dynamic libraries, executables and their dependencies.
It is platform independent and generates makefiles and/or ide project files for most compilers and IDEs.
It abstracts the differences betwe... |
2,486,128 | 2,486,137 | Why aren't return types considered in Java method overloads? | Why return type of a method is not considered in method overloading ?
Can somebody explain , how compiler checks for overloaded methods ?
|
Why return type of a method is not considered in method overloading?
The main reason is that if you did consider this, a lot of function calls become ambiguous if the return value is not assigned to something. For example, which function call is being invoked here?
public String x() { ... }
public int x() { ... }
//... |
2,486,386 | 2,486,395 | Why do I see THROW in a C library? | When I do:
less /usr/include/stdio.h (which is only a C library - nothing to do with C++)
I see __THROW after quite a few function declarations.
Also, comments above a few functions say that 'This function is a possible cancellation point and therefore not marked with __THROW'
What is all this for?
throw is meant to be... | This header is likely shared between the C and C++ compiler for that vendor. Did you look what __THROW is defined as?
I suspect something akin to:
#ifdef __cplusplus
#define __THROW throw()
#else
#define __THROW
#endif
Or for actual specifications:
#ifdef __cplusplus
#define __THROW(x) throw(x)
#else
... |
2,486,406 | 2,486,463 | how to exploit vulnerability of php? | I have never seen a buffer overflow exploit in live action. Suppose I found a server that seems to have vulnerabilities. Where can I get proof of the concept code preferably in c/c++ to exploit the vulnerability? eg I found this vulnerability
Multiple directory traversal vulnerabilities in
functions such as 'pos... | I believe you have somewhat failed to understand the nature of the directory traversal bug.
safe_mode in PHP means that only local filepaths are allowed to be open, rather than allowing any recognizeable protocol such as for example http:// paths. The safe_mode check that verifies wether or not the path is a local file... |
2,486,410 | 2,486,425 | Extra leading zeros when printing float using printf? | I'd like to be able to write a time string that looks like this: 1:04:02.1 hours using printf.
When I try to write something like this:
printf("%d:%02d:%02.1f hours\n", 1, 4, 2.123456);
I get:
1:04:2.1 hours
Is it possible to add leading zeros to a float formatting?
| With the %f format specifier, the "2" is treated as the minimum number of characters altogether, not the number of digits before the decimal dot. Thus you have to replace it with 4 to get two leading digits + the decimal point + one decimal digit.
printf("%d:%02d:%04.1f hours\n", 1, 4, 2.123456);
|
2,486,451 | 2,486,612 | Design question - loading info from DB | I need to build a class that will represent a row in some table in DB (lets say the table is 'Subscriber' and so is the class).
I can have the class Subscriber which constructor receives the Objectkey of subscriber, retrieves info from DB and initializes its members.
I add another class - SubscriberLoader which have a... | I'd recommend the second approach, because it separates two concerns into two separate classes:
the concern of whatever a subscriber is supposed to do
the concern of extracting a subscriber from the database
|
2,486,493 | 2,486,627 | invasive vs non-invasive ref-counted pointers in C++ | For the past few years, I've generally accepted that
if I am going to use ref-counted smart pointers
invasive smart pointers is the way to go
--
However, I'm starting to like non-invasive smart pointers due to the following:
I only use smart pointers (so no Foo* lying around, only Ptr)
I'm starting to build custom all... | There are several important difference between invasive or non-invasive pointers:
The biggest advantage of second (non-invasive):
It is much simpler to implement weak reference to second one (i.e. shared_ptr/weak_ptr).
Advantage of first is when you need to get smart pointer on this (at least in case of boost::shared... |
2,486,713 | 2,488,297 | User defined conversion operator as argument for printf | I have a class that defined a user defined operator for a TCHAR*, like so
CMyClass::operator const TCHAR*() const
{
// returns text as const TCHAR*
}
I want to be able to do something like
CMyClass myClass;
_tprintf(_T("%s"), myClass);
or even
_tprintf(_T("%s"), CMyClass(value));
But when trying, printf always p... | Avoid conversion operators. They rarely do what you want, and then explicit calls are painful. Rename operator const TCHAR*() const to TCHAR *str() const.
|
2,486,727 | 2,486,741 | breaking out from socket select | I have a loop which basically calls this every few seconds (after the timeout):
while(true){
if(finished)
return;
switch(select(FD_SETSIZE, &readfds, 0, 0, &tv)){
case SOCKET_ERROR : report bad stuff etc; return;
default : break;
}
// do stuff with the incoming connection
}
... | The easiest way is probably to use pipe(2) to create a pipe and add the read end to readfds. When the other thread wants to interrupt the select() just write a byte to it, then consume it afterward.
|
2,486,963 | 2,487,029 | microsoft visual studio 2008 builds keep failing | My builds keep failing with the following error
Project : error PRJ0002 : Error result 31 returned from 'C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\mt.exe'.
I find that i have to kill some process called mspdbsrv.exe description:"microsoft program database" Then rebuild the entire project. This is annoying.... | The problem is that for some reason, your mspdbsrv.exe is staying alive after the build. This is what's used to generate your .pdb files as part of the build. The only reliable solution seems to be to kill that process.
What you can do is at least automate that, just add a post-build event and console kill it. I'd s... |
2,487,010 | 2,487,043 | Memory allocation problem C/Cpp Windows critical error | I have a code that need to be "translated" from C to Cpp, and i cant understand, where's a problem. There is the part, where it crashes (windows critical error send/dontSend):
nDim = sizeMax*(sizeMax+1)/2;
printf("nDim = %d sizeMax = %d\n",nDim,sizeMax);
hamilt = (double*)malloc(nDim*sizeof(double));
printf("End ... | On my machine, this program compiles, executes without error and reports no memory problems when run through valgrind. Unless you are running on a small embedded system, your problem is likely something external to this code, because the total amount of memory allocated by this program is less than 140 KiB.
Besides, wh... |
2,487,143 | 2,487,149 | How can I make this function act like an l-value? | Why can't I use the function ColPeekHeight() as an l-value?
class View
{
public:
int ColPeekHeight(){ return _colPeekFaceUpHeight; }
void ColPeekHeight( int i ) { _colPeekFaceUpHeight = i; }
private:
int _colPeekFaceUpHeight;
};
...
{
if( v.ColPeekHeight() > 0.04*_heightTable )
... | Return the member variable by reference:
int& ColPeekHeight(){ return _colPeekFaceUpHeight; }
To make your class a good one, define a const version of the function:
const int& ColPeekHeight() const { return _colPeekFaceUpHeight; }
when I declare the function with the
two consts
When you want to pass an object in... |
2,487,509 | 3,166,936 | Are C++ exceptions sufficient to implement thread-local storage? | I was commenting on an answer that thread-local storage is nice and recalled another informative discussion about exceptions where I supposed
The only special thing about the
execution environment within the throw
block is that the exception object is
referenced by rethrow.
Putting two and two together, wouldn'... | In the playful spirit of the question, I offer this horrifying nightmare creation:
class tls
{
void push(void *ptr)
{
// allocate a string to store the hex ptr
// and the hex of its own address
char *str = new char[100];
sprintf(str, " |%x|%x", ptr, str);
strtok(str, "|"... |
2,487,534 | 2,487,627 | Subtracting months/years from boost::posix_time::ptime | I have a boost::posix_time::ptime that points to March 31st 2010 like this:
ptime p(date(2010, Mar, 31));
I would like to subtract a month (and possibly years) from this date. From the docs I see these two operators: ptime operator-(time_duration) and ptime operator-(days) but none of them can work with months/years... | boost::posix_time::ptime::date() operator returns date object. You can call greg_year, greg_month etc. for this object.
|
2,487,608 | 2,487,641 | what is wrong here? associativity? evaluation order? how to change order? | The associativity of stream insertion operator is rtl, forgetting this fact sometimes cause to runtime or logical errors.
for example:
1st-
int F()
{
static int internal_counter c=0;
return ++c;
}
in the main function:
//....here is main()
cout<<”1st=”<<F()<<”,2nd=”<<F()<<”,3rd=”<<F();
and the output is:
1st=3,... | The only things that are right-associative are the assignment operators. See §5.4 to 5.18 of the standard. The << operators are evaluated left-to-right or the messages would be backward in grammar, not in content. The content is due to side effects, which are unordered in C++ except (as Neil mentions) for "short-circui... |
2,487,653 | 2,487,739 | Avoiding denormal values in C++ | After searching a long time for a performance bug, I read about denormal floating point values.
Apparently denormalized floating-point values can be a major performance concern as is illustrated in this question:
Why does changing 0.1f to 0 slow down performance by 10x?
I have an Intel Core 2 Duo and I am compiling wit... | You can test whether a float is denormal using
#include <cmath>
if ( std::fpclassify( flt ) == FP_SUBNORMAL )
(Caveat: I'm not sure that this will execute at full speed in practice.)
In C++03, and this code has worked for me in practice,
#include <cmath>
#include <limits>
if ( flt != 0 && std::fabsf( flt ) < std::nu... |
2,487,838 | 2,487,856 | Qt: default value of variable in class | When creating my own class in Qt I would like my variables in the class to have a standard/default value if I haven't set them to anything. It would be perfect if this was possible to set in the h-file so I don't have to do it in each instance method of my class. You can see what I want to do in the code below. In the ... | Qt follows the rules of C++, and one rule is to use constructors to initialize your members.
MyClass::MyClass() : myBool(false), myInt(0)
{
}
|
2,487,911 | 2,494,122 | Connecting Arduino to the Internet across a firewall proxy | I have an Arduino with an Ethernet Shield.
How can I connect it to the Internet across a firewall proxy?
For example, the Arduino Ethernet library has only this reference to demonstrate how to connect your board to the Internet but no clue how to do it across firewall proxies, etc.
Repeated from Arduino help pages.
#in... | The Client class supports neither SOCKS nor HTTP proxies. You'll have to modify the code in Ethernet.h yourself.
|
2,487,931 | 5,979,028 | LLVM C++ IDE for Windows | Is there some C/C++ IDE for Windows, which is integrated with the LLVM compiler (and Clang C/C++ analyzer), just like modern Xcode do.
I have Dev-Cpp (it uses outdated GCC) and Code::Blocks (with some GCC). But GCC gives me very cryptic error messages. I want to get some more user-friendly error messages from the Clang... | LLVM is supported in Eclipse CDT via plug-in (llvm4eclipsecdt). It is the only Windows supported IDE supporting LLVM as far as I know. I am the main author of the plug-in so you can ask any questions related to it.
The plug-in offers the basic functionality for Clang and llvm-gcc compilation and support Linux and Windo... |
2,488,199 | 2,488,370 | MinGW Doesn't Generate an Object File When Compiling | I've just bought a new laptop for me on the travel, then on my free time, I've started to test MinGW on it by trying to compile my own OS that is written in C++, then I've created all the files needed and the kernel.cpp:
extern "C" void _main(struct multiboot_data* mbd, unsigned int magic);
void _main( struct multibo... | It doesn't create the file because you have -Werror enabled. The warnings you're getting about unused variables are counting as errors, so compilation gets aborted. Just comment them out for the moment:
void _main( struct multiboot_data* mbd, unsigned int /* magic */ )
{
// char * boot_loader_name =(char*) ((long*)... |
2,488,317 | 2,488,329 | The problem of return reference to local variable |
Possible Duplicate:
Returning reference to a local variable
I happened to find this code return 5. It's OK to write it this way or should definitely be avoid?
int& f() {
int i = 5;
return i;
}
int main(){
cout<<f()<<endl;
}
| If it works, it works only by accident. This is undefined behavior and should definitely be avoided.
The moment that f returns, there are no longer any guarantees as to what happens to the memory where i lived and what happens when you try to access it.
|
2,488,330 | 2,488,348 | Is it possible to Serialize and Deserialize objects in C++? | As we know c++ is also an Object Oriented Programming language where most the things are objects like java. So wanted to know is the Serialize and deserializ features are available in c++ as well as we do it in java?
If yes how it can be achieved?
In java We use Serializable Interface to say that this type of object ca... | Check this out:
http://www.functionx.com/cpp/articles/serialization.htm
or use
Boost:Serialization
http://www.boost.org/doc/libs/1_36_0/libs/serialization/doc/index.html
|
2,488,385 | 2,544,943 | Where to get streaming (live) video and audio from camera example app for Nokia? | Where to get streaming (live) video and audio from camera example for Nokia (5800 for ex)?
Suppose I want to create some live video streaming service app so I'll have some cool server at the back end. And I know how to do that part. Suppose I have some stand alone app for PCs now I want to go on to mobile devices. So I... | Do you already know network protocols used to stream media content, like RTSP?
If not, you probably need to start with that.
You should find good code to start with in the Helix source code.
You may face the usual issue of your network mobile operator filtering out anything but HTTP, which is not a very practical proto... |
2,488,406 | 2,488,507 | Why doesn't c++ have &&= or ||= for booleans? | Is there a "very bad thing" that can happen &&= and ||= were used as syntactic sugar for bool foo = foo && bar and bool foo = foo || bar?
| A bool may only be true or false in C++. As such, using &= and |= is relatively safe (even though I don’t particularly like the notation). True, they will perform bit operations rather than logical operations (and thus they won’t short-circuit) but these bit operations follow a well-defined mapping, which is effectivel... |
2,488,418 | 2,488,525 | Should I pointer-cast from a private derived class to its base class? | I found this from C++FAQ
Generally, No.
From a member function or friend of a
privately derived class, the
relationship to the base class is
known, and the upward conversion from
PrivatelyDer* to Base* (or
PrivatelyDer& to Base&) is safe; no
cast is needed or recommended.
However users of PrivatelyDer shou... | From a purely mechanical viewpoint, you're right: a cast to a private base class will work and produce working results.
The point of the FAQ is that from a design viewpoint it's generally wrong. Private inheritance is really supposed to mean private -- in other words, even though it may work, you're not supposed to kno... |
2,488,513 | 2,488,542 | How do debug header file implemetation (its .cpp) in c++ using GDB | I have these 3 file in my program:
sample1.h (method in sample1.cpp are defined here)
sample1.cpp (all the actual implementations)
demo.cpp (I am using the methods in sampe1.cpp here, and have included sample1.h)
Now, I am using GDB to debug and I know the basic commands like "break lineno." or "break methodname". B... | try
break mymethod
As the function name in not ambiguous, it should work.
See. http://www.unknownroad.com/rtfm/gdbtut/gdbbreak.html#BCPPFUNC
|
2,488,515 | 2,488,553 | Official names for pointer operators | What are the official names for the operators * and & in the context of pointers? They seem to be frequently called dereference operator and address-of operator respectively, but unfortunately, the section on unary operators in the standard does not name them.
I really don't want to name & address-of anymore, because &... | From the C99 draft, at the index:
* (indirection operator), 6.5.2.1, 6.5.3.2
& (address operator), 6.3.2.1, 6.5.3.2
From the C++0x draft, at the index:
*, see indirection operator, see multiplication operator
&, see address-of operator, see bitwise AND operator
It's also referenced in 9.6/3 "The address-of operator... |
2,488,545 | 2,488,653 | Reading bmp file for steganography | I am trying to read a bmp file in C++(Turbo). But i m not able to print binary stream.
I want to encode txt file into it and decrypt it.
How can i do this. I read that bmp file header is of 54 byte. But how and where should i append txt file in bmp file. ?
I know only Turbo C++, so it would be helpfull for me if u prov... | I think you question is allready answered:
Print an int in binary representation using C
convert your char to an int and you are done (at least for the output part)
|
2,488,596 | 2,488,604 | How to return a copy of the data in C++ | I am trying to return a new copy of the data in a C++ Template class. The following code is getting this error: invalid conversion from 'int' to 'int*'. If I remove the new T then I am not returning a copy of the data but a pointer to it.
template<class T>
T OrderedList<T>::get( int k )
{
Node<T>* n = list;
for... | new creates and returns a pointer. You just want a copy which will be created implicitly, since the return statement will invoke the copy constructor (or equivalent for POD) of the object T:
return n->get_data();
|
2,488,730 | 2,489,409 | pyopengl: Could it replace c++? | I'm starting a computer graphics course, and I have to choose a language.
Choices are between C++ and Python. I have no problem with C++, python is a work in progress. So i was thinking to go down the python road, using pyopengl for graphics part.
I have heard though, that performance is an issue.
Is python / pyopengl ... | It depends a LOT on the contents of your computer graphics course. If you are doing anything like the introductory course I've taught in the past, it's basically spinning cubes and spheres, some texture mapping and some vertex animation, and that's about it. In this case, Python would be perfectly adequate, assuming yo... |
2,488,782 | 2,488,812 | Some questions about Vector in STL | I have some questions about vector in STL to clarify.....
Where are the objects in vector allocated? heap?
does vector have boundary check? If the index out of the boundary, what error will happen?
Why array is faster than vector?
Is there any case in which vector is not applicable but array is a must?
|
In a contiguous memory block on the heap. A vector<int> allocates memory the same way new int[x] would.
Only if you use the at method. It throws an std::out_of_range exception if the boundary check fails. The operator[] doesn't perform bounds checking.
Because an array gives direct access to memory, while accessing a ... |
2,488,915 | 2,488,929 | why no += operator for vectors in stl | I am curious? What high fundu logic goes behind not implementing:
result+=vector1;
where both result and vector1 are stl vectors.
Note: i know how to implement that bit, but i need to know what logic, the sages who designed STL were using when they chose not to implement this feature?
| What are you expecting result to contain, the result of concatenating the original result with vector1 or an element-wise += (whatever that means for the underlying types), possibly default-initializing members if the sizes don't match?
And yes, this is an answer ;) .
Operator overloading should only be used where the ... |
2,488,941 | 2,488,957 | Find which numbers appears most in a vector | I have some numbers stored in a std::vector<int>. I want to find which number appears most in the vector.
e.g. in the vector
1 3 4 3 4 2 1 3 2 3
the element that occurs the most is 3.
Is there any algorithm (STL or whatever) that does this ?
| Sort it, then iterate through it and keep a counter that you increment when the current number is the same as the previous number and reset to 0 otherwise. Also keep track of what was the highest value of the counter thus far and what the current number was when that value was reached. This solution is O(n log n) (beca... |
2,489,128 | 2,489,159 | GCC emits extra code for boost::shared_ptr dereference | I have the following code:
#include <boost/shared_ptr.hpp>
struct Foo { int a; };
static int A;
void
func_shared(const boost::shared_ptr<Foo> &foo) {
A = foo->a;
}
void
func_raw(Foo * const foo) {
A = foo->a;
}
I thought the compiler would create identical code, but for shared_ptr version an extra seemingly... | It's not a 'redundant' instruction.
The relevant section of the first code snippet is equivalent to:
*p
Whilst in the second it's equivalent to:
**p
Due to shared_ptr's internals there is a second level of indirection. This is not something the optimizer can 'fix'.
At any rate, the difference is negligible.
EDIT:
Whoop... |
2,489,197 | 2,489,235 | What's the best way to resolve a filepath? | I've got a series of filepaths that look something like this:
C:\Windows\System32\svchost.exe -k LocalSystemNetworkRestricted
C:\Windows\System32\svchost
C:\Program Files (x86)\Common Files\Steam\SteamService.exe /RunAsService
"C:\Program Files (x86)\Common Files\Steam\SteamService.exe" /RunAsService
and I need to fi... | Number 4 should be relatively easy. If the path starts with a " character, just read until the next " and that's the path. With the others, it's slightly more tricky, but the way Windows does it is by simply breaking the command line into parts, and trying one at a time, so looking at #3, it breaks it up into an array ... |
2,489,314 | 2,489,360 | Why is casting Derived** to Base*const* forbidden? | After reading this question, i saw the answer by Naveen containing a link to this page, which basically says, that casting from Derived** to Base** is forbidden since could change a pointer to an pointer to a Derived1 object point to a pointer to a Derived2 object (like: *derived1PtrPtr=derived2Ptr).
OK, i understand t... | First thing is that, if you really need to, you can cast any pointer type to any other pointer type. For instance, you can cast to void* as an intermediate step.
Second, with pointers-to-pointers, it's not so much that there's a reason to make particular cases hard as that there are no special rules to make any particu... |
2,489,321 | 2,489,350 | Static Function Help C++ | I can't get past this issue I am having. Here's a simple example:
class x
{
public:
void function(void);
private:
static void function2(void);
};
void x::function(void)
{
x::function2(void);
}
static void function2(void)
{
//something
}
I get errors in which complain about function2 being p... |
You can't have a function declaration and definition both in a class. Either move the definitions out of the class or remove the declarations.
You can't call a function with a void as a parameter. That is used only in the declaration.
The function definition for function2 if outside the class will need a x:: qualifier... |
2,489,335 | 2,489,485 | What does template<class key, class type> mean before a method in C++? | I have got this code and I am trying to understand the convention followed, all the method defined in the .cpp file have template<class KeyType, class DataType> written before them. What does that mean?
Example:
//Constructor
template<class key, class type>
MyOperation<key, type>::MyOperation()
{
//method implementat... | There has to be a good answer for this already but I'll throw mine into the pool as well.
C++ allows for declarations and implementations of program structures to be done separately. It stems from how C/C++ programmers publish new functionality to each other: header files are included in dependent compilation units ra... |
2,489,379 | 2,492,581 | encrypt- decrypt with AES using C/C++ | How can I encrypt and decrypt a file with a 256 key AES in C or C++?
| If you are just after AES and do not mind losing flexibility (i.e. you will not replace it with another cryptographic algorithm at some time) then Brian Gladman's AES implementation is a popular choice (both for performance and portability). This is the kind of code which you embed in your own source code.
On the exter... |
2,489,387 | 2,489,532 | Differing paths for lua script and app | My problem is that I'm having trouble specifying paths for Lua to look in.
For example, in my script I have a require("someScript") line that works perfectly (it is able to use functions from someScript when the script is run standalone.
However, when I run my app, the script fails. I believe this is because Lua is lo... | You can customize the way require loads modules by putting your own loader into the package.loaders table. See here:
http://www.lua.org/manual/5.1/manual.html#pdf-package.loaders
If you want to be sure that things are nicely sandboxed, you'll probably want to remove all the default loaders and replace them with one tha... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.