I am new to coding and C++ and I am asking myself how to store or structure all these little (sub)functions and code in a proper way?
For example a function to sum up all values of an array or the Fibonacci numbers or all the other little functions and programs which are basic stuff esp. pointers etc.!?
My idea is to create an ordinary .txt sheet and to copy and paste them all there in just one .txt
For me it´s important to have them all at one place. How do you pros handle this or do you guys really have most of this stuff in your local memory (brain). For me it seems impossible to remember all the functions and algorithms or even the syntax (when the code starts to get nasty).
If I understood your question correctly then you are asking where/how we store reusable snippets of code in an easy to access way. There are number of methods to accomplish this, one which you have mentioned is to simply use a text file and copy paste as needed, but in my opinion this is a bit archaic.
I have two main methods I like to use, first if it's code I want to access online or is rather large functions I plan to reuse, I simply make a gist of it and leave it there, ready to be accessed as needed. Usually I name it something descriptive so when I look through all my gists, I can find the ones I need quickly.
The second method, and the stuff I do for code that mainly gets reused is to make snippets using my IDE's configuration files. Such snippets usually are written in JSON format and include a trigger word, for example: for and then when you hit a special key, typically tab, it will expand the snippet to something like:
for(int i = 0; i < n; i++) {
// Code goes here...
}
And we can simply just hit tab to edit the starting condition, the ending condition, the increment and the variable names. Snippets are very versatile and you can write as many as you want. If you use Visual Studio Code you can take a look at the C++ tools extension which has some default snippets.
Lastly I keep a handy bookmark to a C++ reference site and look up stuff in the STL as needed so I'm not reinventing the wheel or making extra work for myself.
Welcome to StackOverflow!!!
In C++ you generally put all your functions in a header and cpp file to store all the functions. You then go to the main and pick up a reference to the header file.
// A2DD.h
#ifndef A2DD_H
#define A2DD_H
namespace A2DD{
int GetSum(int x, int y);
}
#endif
and the implementation goes in the CPP file:
// A2DD.cpp
#include "A2DD.h"
int A2DD::GetSum(int x, int y){
return x + y;
}
Then go the main.cpp
#include "A2DD.h"
int main(){
std::cout << GetSum(2, 2) << std::endl;
}
As far as remembering the functions, you can simply take a quick look at the header file which declares the functions (no implementation)
I have a problem with my code, it seems to fail in a weird way in release mode, debug mode works just fine.
I am out of ideas and clues. I would like to get a direction for what should i do.
So here is the problematic code:
static inline void FindPoint(Line *First,AABB *Second,point *Pt,int direction)
{
std::vector<point*> pntvec; ... }
When i call function FindPoint it is all fine and everything is set well.
But when i reach the vector initialization the First pointer is reset to the same address as the vector.
That causes unexpected behavior.
So i thought the problem was in the commonalities. Both Line and the vector are using the point structure.
Yet i was not able to find anything unusual.
here are the structures
typedef struct
{
double x;
double y;
}point;
typedef struct
{
double incline;
double y;
double x;
double c;
point start,finish;
}Line;
And here is the initialization of the data sent to parameter First:
Line *objvec = new Line;
so what could be the problem can any one tell?
Thank you in advance
Edit:
A better look at the code
http://pastebin.com/rki7EdM6
You're using pointers more heavily than you should for these simple types. Pointers and dynamic allocation are the likely sources of your undefined behavior. So a simple first step is to refactor and clean up your code, preferring stack variables and pass-by-reference for simple types. In all likelihood, the undefined behavior will go away, or the error will be easier to spot.
[Caveat: I can't get to pastebin, so I can't see your full code. Prefer simple examples right here on the site]
For example, your function signature should probably be this (I'm guessing about which parameter is the output)
static inline point FindPoint(const Line &First, const AABB &Second,int direction)
And
Line *objvec = new Line;
should just be
Line objvec;
etc, etc.
std::vector<point> pntvec;
is probably the most important. A vector of pointers is ok, but should be avoided if possible. One of the nice parts about standard containers is the auto-cleanup when the variable goes out of scope. You don't get that with a vector of pointers, since the vector doesn't know to call delete on every element. You have to do it yourself.
"so what could be the problem can any one tell?"
If such a situation occurs, the most probable reason is, you have hit undefined behavior in your code somewhere else.
I can't tell any more from the context and code you have posted. But using a tool like valgrind is likely to do this right on your service.
Okay, I have a struct, TextBlock, that simulates moving blocks of text around the screen. Here's the header:
struct TextBlock
{
RECT textArea;
RECT rectArea;
double whatBlock;
double x;
double y;
double angle;
double speed;
double width;
double height;
char *word;
bool stuck;
};
When it's like this, everything works perfectly fine. The problem comes when I add another member that I need. The way it works is that I have two arrays of TextBlocks. The first is for moving ones, the second is for ones that don't move, signifying where the moving ones need to go. The words are all randomized from a sentence to a jumble, so this data member will be set (commented out) to the index of which static block belongs to the moving one so I know when it's in the right place.
int whatBlock;
After creating this, I go through all of the created objects and set
tb[i][j].whatBlock = 0; //same area as other data members being set, moving text
stb[i][j].whatBlock = 0; //static text block
When I try to run this, without doing anything else to the data member, it comes up with an error:
The instruction at [address] referenced memory at [different address]. The memory could not be "written".
Note that if I don't try to modify it, and just create the data member, it works.
At this point of almost being done and having tons of these kinds of problems, I'm getting a bit fed up with this program >.> Any help at all on this would be greatly appreciated.
EDIT: This issue is now fixed. I replied to the accepted answer with the explanation, but it poses another problem, even if it doesn't affect this program.
Force a rebuild of everything. You may have an object file that is out-of-date with respect to the header file that defines TextBlock
If that doesn't fix it, run your program under a debugger and see what the faulting instruction is. Either that will allow you to fix the program, or you can ask again with mroe informatin.
Without you posting more code, I can only tell that you likely have a memory corruption bug in your program - i.e. you are reading or writing beyond the end of allocated memory.
If you post more code, I'll edit this answer accordingly.
I can't really give advices since we cannot access the complete source code.
Anyway, I can suggest you that it may be not in the struct TextBlock where really hides the bug. For instance, every access to TextBlock's member means that you are accessing to this hidden variable.
If this pointer is corrupted, you may experience problem where you don't expect it, leading you to search in the wrong places.
I have a class like this:
class Player
{
public:
Player(Board * someBoard);
void setSide(char newSide);
protected:
Board * board;
char side;
};
and its implementation is as such:
Player::Player(Board * someBoard)
{
board = someBoard;
side = '0';
}
void Player::setSide(char newSide)
{
side = newSide;
}
Now I have another class inheriting from it:
class HumanPlayer : public Player
{
public:
HumanPlayer(Board * someBoard);
};
And its short implementation is this:
HumanPlayer::HumanPlayer(Board * someBoard) : Player(someBoard)
{
}
Now the problem is the side = '0'; line makes the program freeze (the window turns white in Windows 7, not sure if that means it froze or crashed). Commenting it out make the program run fine (and it's okay to comment it out because the variable isn't used anywhere yet).
What is causing the error and how can I fix it?
EDIT!
After printing out some stuff to an fstream, all of a sudden the program worked. I tried commenting the printing out. It still worked. I tried deleting the debugging code I added in. It still worked. So now my code is exactly the same as listed above, but it magically works now.
So what do I do now? Ignore the anomaly? Could it have been a compiler mistake?
I suspect the problem isn't what you think it is.
It sounds like a memory corruption issue of some sort, but it's really impossible to tell based on the information provided. I have two suggestions for you:
Either post the smallest complete program that demonstrates the problem, or
Try a valgrind-type tool to see if it helps you figure out what's going on.
Or, better yet, start by looking at the state of the program in the debugger (once it's hung.)
Is it possible that you are using two incompatible definitions of your Player class, defined in different header files? If the definitions have different sizes, then the 'size' member might lie outside the memory block allocated for the class instance.
Edit I see that your problem has disappeared. So it was probably a module that didn't get re-compiled after a change in the class definition; but now that you've re-compiled everything, the problem has fixed itself.
At a previous employer, we were writing binary messages that had to go "over the wire" to other computers. Each message had a standard header something like:
class Header
{
int type;
int payloadLength;
};
All of the data was contiguous (header, immediately followed by data). We wanted to get to the payload given that we had a pointer to a header. Traditionally, you might say something like:
char* Header::GetPayload()
{
return ((char*) &payloadLength) + sizeof(payloadLength);
}
or even:
char* Header::GetPayload()
{
return ((char*) this) + sizeof(Header);
}
That seemed kind of verbose, so I came up with:
char* Header::GetPayload()
{
return (char*) &this[1];
}
It seems rather disturbing at first, possibly too odd to use -- but very compact.
There was a lot of debate on whether it was brilliant or an abomination.
So which is it - Crime against coding, or nice solution? Have you ever had a similar trade-off?
-Update:
We did try the zero sized array, but at the time, compilers gave warnings.
We eventually went to the inhertited technique: Message derives from Header.
It works great in practice, but in priciple you are saying a message IsA Header - which seems a little awkward.
I'd go for crime against coding.
Both methods will generate the exact same object code. The first makes it's intention clear. The second is very confusing, with the only advantage that it saves a couple keystrokes. (Just learn to freakin' type).
Also, note that NEITHER method is guaranteed to work. The sizeof() an object includes padding for word alignment, so that if the header was:
class Header
{
int type;
int payloadLength;
char status;
};
Both methods you describe would have the payload starting at Header+12, when most likely it actually starts at Header+9.
You're depending on the compiler to layout your classes in a particular way. I would have defined the message as a struct (with me defining layout) and had a class that encapsulates the message and provides the interface to it. Clear code = good code. "Cute" code = bad (hard to maintain) code.
struct Header
{
int type;
int payloadlength;
}
struct MessageBuffer
{
struct Header header;
char[MAXSIZE] payload;
}
class Message
{
private:
MessageBuffer m;
public:
Message( MessageBuffer buf ) { m = buf; }
struct Header GetHeader( )
{
return m.header;
}
char* GetPayLoad( )
{
return &m.payload;
}
}
It's been awhile since I've written any C++, so please excuse any issues with syntax. Just trying to convey the general idea.
Personally I think that if there's a crime, it's asking the header for the payload.
But as long as you're going to do it that way, 'this+1' is as good a way as any.
Justification: '&this[1]' is a general-purpose piece of code that doesn't require you to go digging through class-definitions to fully comprehend, and doesn't require fixing when someone changes the name or contents of the class.
BTW, the first example is the true crime against humanity. Add a member to the end of the class and it'll fail. Move the members around the class and it'll fail. If the compiler pads the class, it'll fail.
Also, if you're going to assume that the compiler's layout of classes/structs matches your packet layout, then you should understand how the compiler in question works. Eg. on MSVC you'll probably want to know about #pragma pack.
PS: It's a little scary how many people consider "this+1" or "&this[1]" hard to read or understand.
It's a common problem, but what you actually want is this.
class Header
{
int type;
int payloadLength;
char payload[0];
};
char* Header::GetPayload()
{
return payload;
}
My vote is Coding Horror. Don't get me wrong, it's clever - but you're saving yourself one entire addition operation at the cost of making the code much more difficult to understand and read. I don't see the tradeoff as worth it.
I think this is flawed from the start on if the header needs to "return" data which is not included in it.
As you already put yourself on these hackish grounds, I really love what you came up with.
But note that this is not a beauty contest. You should find an entire different solution. For alle the three versions of GetPayload() you presented, I would not understand what the hell is going on there without your further explanation.
Have you considered the 'empty array member' trick? I remember seeing it often, and even using it once or twice, but I can't seem to find any really good references (except, maybe, the one referenced below).
The trick is to declare your struct as
struct bla {
int i;
int j;
char data[0];
}
Then, the 'data' member simply points to whatever is behind the headers. I am not sure how portable this is; I've seen it with '1' as the array size as well.
(using the URL below as a referece, using the '[1]' syntax, seemed not to work because it is too long. Here is the link:)
http://developer.apple.com/documentation/DeveloperTools/gcc-4.0.1/gcc/Zero-Length.html
If it works -- consistently -- then it's an elegant solution.
It will normally work in memory because the compiler will deal with alignment issues and you can assume that the Payload follows the header in correctly-aligned memory space.
I could see this falling apart when the Header/Payload objects are streamed "over the wire" because the streaming mechanism you use will probably not care about aligning objects on any particular boundary. Therefore, Payload may directly follow the Header with no padding to force it to a particular alignment.
To coin a phrase, elegant is as elegant does. So, it's elegant as long as you are careful how you stream it.
First, there's an awful lot of space between "crime against coding" and "nice solution," but I'd say this is closer to the former.
Is the Header its Payload's keeper?
That's the fundamental problem here -- both the header and the payload should be managed by another object that holds the entire message, and that is the proper place to ask for the payload. And it would be able to do so without pointer arithmetic or indexing.
Given that, I would favor the second solution, since it is clearer what is going on.
But that we're in this situation to begin with seems to indicate that the culture of your team values cleverness over clarity, so I guess all bets are off.
If you really want to be cute, you could generalize.
template<typename T. typename RetType>
RetType JustPast(const T* pHeader)
{
return reinterpret_cast<RetType>(pHeader + sizeof(T));
}
They're basically the same thing as far as I'm concerned. Both are forms of byte juggling, which is always risky, but not impossible to get right.
The first form is a bit more accepted and recognizable.
I would personally write :
char* Header::GetPayload()
{
return ((char*) this) + sizeof(*this);
}
Don't forget that VC++ may impose a padding on the sizeof() value on the class. Since the provided example is expected to be 8 bytes, it is automatically DWORD aligned, so should be ok. Check #pragma pack.
Though, I agree, the provided examples are some degree of Coding Horror. Many Win32 data structures include a pointer placeholder in the header structure when variable length data follows. This is probably the easiest way to reference this data once it's loaded into memory. The MAPI SRowSet structure is one example of this approach.
I actually do something similar, and so does nearly every MMO or online video game ever written. Although they have a concept called a "Packet" and each packet has it's own layout. So you might have:
struct header
{
short id;
short size;
}
struct foo
{
header hd;
short hit_points;
}
short get_foo_data(char *packet)
{
return reinterpret_cast<foo*>(packet)->hit_points;
}
void handle_packet(char *packet)
{
header *hd = reinterpret_cast<header*>(packet);
switch(hd->id)
{
case FOO_PACKET_ID:
short val = get_foo_data(packet);
//snip
}
}
And they do that for the majority of their packets. Some packets obviously have dynamic sizes, and for those members they use length prefixed fields and some logic to parse that data.
I think in this day and age, in C++, the C-style cast to char* disqualifies you from any "brilliant design idea" awards without getting much of a hearing.
I might go for:
#include <stdint.h>
#include <arpa/inet.h>
class Header {
private:
uint32_t type;
uint32_t payloadlength;
public:
uint32_t getType() { return ntohl(type); }
uint32_t getPayloadLength() { return ntohl(payloadlength); }
};
class Message {
private:
Header head;
char payload[1]; /* or maybe std::vector<char>: see below */
public:
uint32_t getType() { return head.getType(); }
uint32_t getPayloadLength() { return head.getPayloadLength(); }
const char *getPayload() { return payload; }
};
This assumes C99-ish POSIX, of course: to port to non-POSIX platforms you'd have to define one or both of uint32_t and ntohl yourself, in terms of whatever the platform does offer. It's usually not hard.
In theory you might need layout pragmas in both classes. In practice I'd be surprised given the actual fields in this case. The issue can be avoided by reading/writing the data from/to iostreams one field at a time, rather than trying to construct the bytes of the message in memory and then write it in one go. It also means you can represent the payload with something more helpful than a char[], which in turn means you won't need to have a maximum message size, or mess about with malloc and/or placement new, or whatever. Of course it introduces a bit of overhead.
Perhaps you should have used a verbose method, but replaced it with a #define macro? This way you can use your shorthand when typing, but anyone needing to debug the code can follow along without issue.
I vote for &this[1]. I've seen it used quite a bit when parsing files that have been loaded into memory (which can equally include received packets). It may look a tad odd the first time you see it, but I think that what it means should be immediately obvious: it's clearly the address of memory just past this object. It's nice because it's hard to get wrong.
I don't like to use words like "crime". I would rather point out that &this[1] seems to make assumptions about memory layout that a compiler might disagree with. For example, any compiler might, for its own reasons (like alignment), insert dummy bytes anywhere in a structure. I would prefer a technique that has more of a guarantee of getting the correct offset if compilers or options get changed.
In addition to the abovementioned, I'd say that this is a crime against interoperability and good wire protocol design principles. It is really surprising how many programmers are not able/willing to make a clear distinction between a wire protocol definition and its implementation.
If your protocol has to survive for more than two days, it most probably has to survive for more than two years/OSes/compilers/languages/endiannesses and in some point it will break, rather sooner than later. So, make other folks' life easier, write down the wire protocol specification plus write proper (de)serialization routines. Otherwise, people will keep mentioning your name in not so pleasant contexts.