Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
TSDK
Nov 24, 2003

I got a wooden uploading this one

Erwin posted:

Horrible newbie question:

In this code:
code:
sprintf (ProdChar, "%d", Product);
...is there any reason that an int called Greatest that has nothing to do with this line would change? If I cout << Greatest just before and just after the line, the output is
code:
9009
8960
But once it's 8960, it stays 8960 even though it goes through this line several more times. Witchcraft is the only explanation I can come up with. :tinfoil:
You've not counted the zero terminator when working out ProdChar's size.

How do I know?

9009 = 0x2331
8960 = 0x2300

So the least significant byte of Greatest has been stomped on. Which then tells me you're running on a little endian machine, and that ProdChar and Greatest have been declared right next to each other.

Adbot
ADBOT LOVES YOU

TSDK
Nov 24, 2003

I got a wooden uploading this one

Plastic Jesus posted:

I came across this a year or two ago:
Good christ, that guy's an idiot. My rule is that for each and every header, it should be possible to have a 2-line source file with:
code:
#include "HeaderFile.h"

That compiles without errors.

The reason why header files often get unruly is that people often #include when a simple forward declaration would be enough, there's not enough seperation of concepts in the source code structure, and people all too often get lazy with includes and form a single "IncludeFeckingEverything.h" header.

TSDK
Nov 24, 2003

I got a wooden uploading this one

Plastic Jesus posted:

Yes, Rob Pike is an idiot.
TSDK's Law: Everyone is an idiot.

It doesn't matter how smart someone is, there is always some topic or opinion about which that person is an idiot. Of course, people often don't realise that they're an idiot about that particular thing. If they did, then by definition they would not be an idiot about it.

The smartest people are the ones who realise that there are things about which they are an idiot (see also: Socrates ;))

TSDK
Nov 24, 2003

I got a wooden uploading this one

Adiabatic posted:

Hi all, I'm currently taking an entry-level C++ programming class and can't for the life of me think of where to begin on this one.

quote:

Students: don't ask or discuss how to get around your school's network security, and don't ask for help with your homework. If you really must ask the internet for help with an assignment, try the Science, Philosophy, and Education subforum.

Read your notes and ask your TA. Feel free to come back and ask specific language related problems when you get stuck, but don't expect to be spoon-fed.

TSDK
Nov 24, 2003

I got a wooden uploading this one

Citizen Erased posted:

Does anyone know of a faster alternative to the standard library vector container? A year or so ago I made a 3D application which relied very heavily on the stl vector and since, a friend has told me how slow vectors are. I'd like to re-work some of the old code and replace the vectors with something similar but more efficient if it means I can eek a few more frames per second out of it. Is there anything faster and more suited for real time 3D applications?
There's nothing intrinsically wrong with using a vector for real-time applications, provided you're not doing something silly with them like re-creating them with push_backs on a per frame basis, or copying them wholesale. In fact, if the vector doesn't resize, then they should be pretty much as fast as a plain array.

It's more likely that any performance problems are down to your use of allocations rather than choice of an STL container.

Also, I'd avoid listening to your friend on matters of performance in future.

EDIT: Check out Meyers' Effective STL if they've got a copy in a library near you.

TSDK
Nov 24, 2003

I got a wooden uploading this one

Vanadium posted:

It says

code:
foo.cpp:16: error: cast from ‘Node*’ to ‘uint’ loses precision
foo.cpp:16: error: cast from ‘Node*’ to ‘uint’ loses precision
for me :shobon:
The clue's in the message then: don't cast to uint.

TSDK
Nov 24, 2003

I got a wooden uploading this one

elevatordeadline posted:

I don't get it, though. The new codepad output is still correct, but mine is still nonsense.
I think your dev environment is misconfigured. By the looks of it, either there's a mismatch in the calling convention or the long double support between your executable and the library you're linking against.

TSDK
Nov 24, 2003

I got a wooden uploading this one

vanjalolz posted:

Another book is needed, one which teaches C and programming at the same time.
By far the best book for this is Kelley & Pohl's A Book on C.

TSDK
Nov 24, 2003

I got a wooden uploading this one

Viper2026 posted:

code:
result = new string[sizeof(list)];
This is almost certainly not doing what you think it's doing.

TSDK
Nov 24, 2003

I got a wooden uploading this one

6174 posted:

Now this does mean that the program didn't correctly function earlier since the constant would need to be \033, not \33,
Nope, the '33' is taken to be octal. You can only specify numeric escape sequences as either octal or hexadecimal.

I've started looking at '\0' in a whole new light since I found out it's a second-class octal zero and not a good and proper decimal zero.

TSDK
Nov 24, 2003

I got a wooden uploading this one

Staggy posted:

If I build in Debug I get that error, but if I switch to Release to build I get
An unresolved WinMain means that you've written it as standard C/C++ with a main function, but are compiling it with SubSystem (Properties->Linker->System) set to Windows instead of Console.

TSDK
Nov 24, 2003

I got a wooden uploading this one
For reference, it's commonly called the 'pimpl idiom' in C++, and more generally known as an 'opaque pointer':
http://en.wikipedia.org/wiki/Opaque_pointer

TSDK
Nov 24, 2003

I got a wooden uploading this one

chutwig posted:

The problem that I'm having seems to be a problem with allocating memory. sizeof(active_query_t) returns 80, which seems too small, since this is the definition of the struct:
code:
gint64 datid;
gint32 procpid;
GString *current_query;
GString *backend_start;
GString *datname;
time_t bs_time_t;
struct tm *bs_tm;
gboolean notified;
GString *hash;	
gint32 hash_len;
gint64 is 8 bytes, gint32 is 4 bytes, GString is 24 bytes, time_t is 8 bytes, tm is 56 bytes, gboolean is 4 bytes. If I add these all up myself, I get 180 bytes.
current_query et al are pointers to GString objects, likewise bs_tm is a pointer to a tm struct.

I'd recommend reading chapter 5 of K&R for starters.


EDIT: Your current crash is because bs_tm is an uninitialsed pointer to a random bit of memory that you're then trying to write to, but if you don't understand pointers then you're going to run into yet more problems real soon.

TSDK fucked around with this message at 17:35 on Jun 12, 2008

TSDK
Nov 24, 2003

I got a wooden uploading this one

chutwig posted:

Just telling somebody to read K&R again doesn't help much when dealing with something like pointers that is very complex.
Well chapter 5 is one of the best and most concise explanations of pointers, so it is well worth giving it another read. It's certainly a much better explanation than anything I could have typed in response.

TSDK
Nov 24, 2003

I got a wooden uploading this one

Zombywuf posted:

Yeah, I do wonder how many problems could be solved with:
Probably not as many as you'd cause. It's bad form in C to cast the result of malloc, because of the rules on implicit declarations for functions. Putting those casts would suppress compile errors caused by missing header file includes and cause a linker error.

TSDK
Nov 24, 2003

I got a wooden uploading this one
The compiler doesn't know whether you want to implicitly convert 2 to a cFp, or f to an int.

Get rid of those user defined cast operators in cFp and replace them with:
code:
    // casting operators
    int as_int() const { return ...; }
    float as_float() const { return ...; }

TSDK
Nov 24, 2003

I got a wooden uploading this one
Here's a dirt-simple process wrapper app I did a while ago. We used it to launch windowed apps from a batch file (as part of an automated asset building process) so that the batch file would wait until the app had closed down before carrying on.
code:
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
#include <string>

int main( int argc, char *argv[] )
{
    // Make sure we have enough paramaters
    if ( argc < 2 )
    {
        printf( "ERROR: Not enough arguments\n" );
        printf( "USAGE: %s <process_name> <optional_arguments>\n", argv[0] );
    }

    // Get the process arguments
    std::string command_line;
    for ( int i = 1; i < argc; i++ ) // Include the module name in the command line
    {
        std::string argument( argv[i] );
        if ( argument.find( ' ' ) == std::string::npos )
        {
            command_line += argument + std::string( " " );
        }
        else
        {
            command_line += std::string( "\"" ) + argument + std::string( "\" " );
        }
    }
    char *p_argument_buffer = new char[command_line.size()];
    memset( p_argument_buffer, 0, command_line.size() );
    memcpy( p_argument_buffer, command_line.c_str(), command_line.size() - 1 ); // Strip the trailing space

    printf( "Executing:-\n\tProcess: %s\n\tArguments: %s\n", argv[1], p_argument_buffer );

    // Set the starting parameters
    STARTUPINFO startup_info = { 0 };
    startup_info.cb = sizeof( startup_info );
    startup_info.dwFlags = STARTF_USESHOWWINDOW;
    startup_info.wShowWindow = SW_MINIMIZE;

    PROCESS_INFORMATION process_info = { 0 };

    // Start the child process. 
    BOOL create_status = CreateProcess( NULL,
                                        p_argument_buffer,
                                        NULL,
                                        NULL,
                                        FALSE,
                                        0,
                                        NULL,
                                        NULL,
                                        &startup_info,
                                        &process_info );

    // Free up our command line
    delete[] p_argument_buffer;

    // Either wait, or throw an error
    if ( create_status == 0 )
    {
        printf( "ERROR (0x%08x): Could not create process %s\n", GetLastError(), argv[1] );
    }
    else
    {
        printf( "Waiting... " );

        // Wait for the process to finish
        WaitForSingleObject( process_info.hProcess, INFINITE );

        // Close process and thread handles.
        CloseHandle( process_info.hProcess );
        CloseHandle( process_info.hThread );

        printf( "Finished\n" );
    }

    return ( create_status == 0 ? -1 : 0 );
}

Enjoy!

TSDK
Nov 24, 2003

I got a wooden uploading this one

tyrelhill posted:

I'm trying to const_cast a class * const to a class * and getting an access violation exception. I'm guessing there's some assembly optimizations with pointer consts that I dont know?
Modifying an object that was declared as const is undefined behaviour. You can only (safely) cast away const-ness to modify something if you know it was declared non-const.

TSDK
Nov 24, 2003

I got a wooden uploading this one

Hammerite posted:

I didn't follow your advice on changing to using std::string, because I couldn't work out how to make that work;
The std::string class isn't all that difficult, so it's worth your while finding a tutorial.
code:
#include <string>

...

std::string coloursay[4] = { "Red", "Yellow", "Green", "Purple" };

...

std::string line1msg = "It's " + coloursay[turnorder[0]] + "'s first turn. Click OK when ready.";
Should work.

TSDK
Nov 24, 2003

I got a wooden uploading this one

ZorbaTHut posted:

For example:
code:
string mystring = getdata();
for(int i = 0; i < mystring.size() - 1; i++) doThings(mystring[[b][/b]i]);
Do you have something against the last character in a string or something?

To me, that just looks like a bug caused by someone mixing and matching C style string handling code with C++ string types. That class of bug is quite hard to introduce when using iterators as designed.

TSDK
Nov 24, 2003

I got a wooden uploading this one

more falafel please posted:

You have absolutely no understanding of what you're talking about.
I think ZorbaTheHut probably just phrased that badly there, rather than being out and out wrong.

If the 'real world' distribution of numbers that your application is handling follows a power law distribution:
http://en.wikipedia.org/wiki/Power_law
Then let's suppose out of 100,000 cases your variable foo will be asked to handle values in the range 0-2147483647 in 96,000 of those cases. There will then only be something like 3,000 cases where it'll be asked to handle values in the range 2147483648-4294967296.

When talking about failures caused specifically by unchecked integer overflow, using an unsigned int instead of an int doesn't actually improve all that much on your rate of failure in general. You then have to weight up the relatively small gain in failure rate versus the likelihood that unsigned ints could cause a problem.

In my opinion, the likelihood that an unsigned int would cause a problem relative to a signed int is very very small indeed, so I'll take that failure rate improvement happily and go on my merry unsigned way.

In a related anecdote, I've been bitten before by using video encoder software that just gave up after the first 2Gb of a 3Gb file and blanked the image (but not the sound) for the last 3rd of the movie clip. Clearly someone with an always-int mentality had written the file loader for the image compression part, and someone with an unsigned-int-mentality had written the file loader for the sound compression part :)

TSDK
Nov 24, 2003

I got a wooden uploading this one
It sounds a bit like you've just not declared the OnInit function in your base state class as virtual. You'll need to post more code to help pinpoint what's going wrong.

Have you tried putting a breakpoint in the stateManager::ChangeState function and tracing into the OnInit function call to see where it ends up?

Finally, I'm not 100% sure what you're trying to do with the logic in the changeState function, but it's almost certainly much more complicated than it needs to be. Split it into three functions: SetState, PushState and PopState.

TSDK
Nov 24, 2003

I got a wooden uploading this one

Staggy posted:

I figured that this way, all you had to do was shove in the address of the state, and the function would work out the rest. Is this a bad way of going about things?
The main reason why it's bad is that the function can end up doing one of several things. It's more of a PushOrPopOrDoNothingOrPossiblySomethingElse() function. It's generally good programming practice for functions to do just one simple job, so that it's easy to use and easy to get right.

So if you have a PushState function, then it's always going to do exactly what you expect it to do: push a state on the stack - nothing more, nothing less.

TSDK
Nov 24, 2003

I got a wooden uploading this one

Entheogen posted:

does it copy in the example I had?
No, it doesn't. I'd be tempted to do something like this though:
code:
std::vector<int> vecs[2];
int current_vector = 0;
while ( some_condition )
{
    // Get a reference to the current vector for convenience
    std::vector<int> &vec = vecs[current_vec];

    // Use vec
    ...

    // Swap currently active vector
    current_vec = 1 - current_vec;
}
I personally think that makes it a bit clearer that you're alternating between the two different vectors, and by having the reference variable 'vec' in the loop, you're making it clear that it's just there to refer to one of a possible set of vectors, and not for any other purpose.

TSDK
Nov 24, 2003

I got a wooden uploading this one

Avenging Dentist posted:

Yes.
Some compilers will do Named Return Value Optimisation as well as just Return Value Optimisation:
http://msdn.microsoft.com/en-us/library/ms364057(VS.80).aspx

TSDK
Nov 24, 2003

I got a wooden uploading this one

Big Mark posted:

What, precisely, is the difference between a reference to a variable and a pointer to it? I've always thought of a reference as being a pointer with nicer syntax but apparently this is very very wrong.
References don't even need to be pointers. For example, if you wrote:
code:
int main()
{
    int a = 10;
    int &b = a;
    b = 20;
    printf( "%d", a );
}
Then the compiler would almost certainly produce identical code to:
code:
int main()
{
    int a = 10;
    a = 20;
    printf( "%d", a );
}
There's also some additional rules about const references to temporaries affecting the lifetime of those temps, but nothing that comes up as a regular occurence.

TSDK
Nov 24, 2003

I got a wooden uploading this one

JoeNotCharles posted:

Isn't "well-formed" a compile-time concept? So how can it depend on the runtime value of p?
Yes, 'well-formed' is as you say, a compile-time concept. It is impossible in general for a compiler to tell you that a C++ program contains no undefined behaviour (and so is well defined) because to do so you would need to solve the halting problem.

TSDK
Nov 24, 2003

I got a wooden uploading this one
I prefer the following syntax for the flag declarations:
code:
enum eMyFlags
{
    MyFlag1 = 1 << 0
    MyFlag2 = 1 << 1
    MyFlag3 = 1 << 2
    MyFlag4 = 1 << 3
};
It's a bit more self-documenting that way, and more easier to write than to keep shuffling powers of two lists around.

Importantly, don't forget to cast the flags to integer types within the operator| and operator& definitions, otherwise you'll end up with an infinite recursive function.

TSDK
Nov 24, 2003

I got a wooden uploading this one

my stepdads beer posted:

I wrote a simple little c program that forks and the child execs another little program. Before the fork, I set up an alarm and signal handler. Now, I thought the child was entirely replaced (in memory) by whatever program it execs, yet the child still seems to be terminated by the alarm I set before the fork.

Can someone set me straight please?
This page does confirm that the alarm should have been cancelled:
http://www.opengroup.org/onlinepubs/000095399/functions/fork.html

Are you sure you haven't got the parent/child processes mixed up?

TSDK
Nov 24, 2003

I got a wooden uploading this one

my stepdads beer posted:

Well they both terminate at the same time (both are writing to stdout continuously). I can't find the child process running after either. Have I written a zombie? :(
I seem to remember (but my memory on this is a bit dusty) that forked child processes terminate when their parents do. I also seem to remember that there are calls you can make to detach a child so that this doesn't happen, but someone else with more recent experience will have to chime in on that one.

TSDK
Nov 24, 2003

I got a wooden uploading this one

tyrelhill posted:

Does it actually compile differently or?
Ignoring possible overloads, then it should compile to identical code.

I've worked with people who prefer the '== false' on negative conditions, but omit the '== true' for positive conditions, on the grounds that it's harder to misread compared to the possibility of not spotting a small '!' tacked on to the front.

TSDK
Nov 24, 2003

I got a wooden uploading this one

Ledneh posted:

drat, I've managed to confuse myself completely this time. In C++, how do I write a typedef for a function pointer where the function would have a templated parameter?

I thought it would be something like this, but the compiler pukes all over it on the basis that the template keyword is only a valid keyword for functions and classes:
code:
template <class T>
typedef void (*TRejectFunc)(CDataRecord<T>, float);
I'm led to believe this means that function pointers cannot be templated; they have to be specialized. If this is the case, I'm kinda hosed; please tell me it's not.
Use a typedef within a templated class. Something like:
code:
template < typename T >
struct TRejectFunc
{
    typedef void (*type)( CDataRecord< T >, float );
};

...

TRejectFunc< int >::type my_reject_function_ptr;

TSDK
Nov 24, 2003

I got a wooden uploading this one
What's the prize?

50

EDIT: Bonus nerd points - your program is ill formed because main should be declared to return an int.

TSDK
Nov 24, 2003

I got a wooden uploading this one

TheSleeper posted:

Uh, exactly how can a bias be evenly distributed? Isn't that the opposite of bias?
I think Zorba's just referring to the fact that not all implementations of rand() have a uniform distribution. In fact, some of the most common implementations are shockingly bad.

TSDK
Nov 24, 2003

I got a wooden uploading this one

Lexical Unit posted:

In general you should probably try and clean up whenever you don't need to hold on to the memory anymore, it's just a good habit to get into.
This. You never know when someone's going to stuff a for loop around the main body of your code and turn it into a batch process, or stick a few __declspecs in and turn it into a DLL.

TSDK
Nov 24, 2003

I got a wooden uploading this one

Avenging Dentist posted:

C++ templates are Turing-complete, assertion destroyed. :c00lbert:
code:
bool will_halt = HaltingChecker< MyClass >::result;
Assertion verified.

TSDK
Nov 24, 2003

I got a wooden uploading this one

Gary2863 posted:

I have no idea how to do this.
There are quite a few easy ways you could do this. Using sprintf and then manipulating the buffer afterwards springs to mind for starters. You could also do a variation on a very typical beginner's textbook problem of extracting the digits one at a time, although you would then either have to make an assumption about the largest possible number or count the digits in some way.

EDIT: Now that you've been given a massive hint, I'll leave the fine details as a good learning exercise for you to do ;)

TSDK
Nov 24, 2003

I got a wooden uploading this one

Avenging Dentist posted:

All you really need is K&R. C is a very simple language.
Kelly & Pohl's A Book on C is an excellent introductory text - better than K&R for a first timer. Then once you've read it, sell it and buy K&R.

TSDK
Nov 24, 2003

I got a wooden uploading this one

Jimmeeee posted:

is there any way someone can write me a program in C that can edit text files in linux. I'd need just the source code.
Here you go:
http://svn.savannah.gnu.org/viewvc/trunk/nano/src/?root=nano


Or alternatively, you could grab yourself a copy of Kelley & Pohl's A Book on C to help you out with your course.

Adbot
ADBOT LOVES YOU

TSDK
Nov 24, 2003

I got a wooden uploading this one

Bitruder posted:

I am using g++ 4.3.2 on a 64-bit Linux Machine.

When I compile my code with -Wall I get the following two warnings:
code:
net.cpp:268: warning: statement has no effect
net.cpp:272: warning: statement has no effect
The thing is, these two statements clearly DO have effects:
code:
266         // Load Each Input
267         pElem = hRoot.FirstChild( "input" ).Element();
268         for( [b]pElem[/b]; pElem; pElem = pElem->NextSiblingElement("input")) {
269             params.clear();
270             hInput = pElem;
271             pElemParam = hInput.FirstChild( "param" ).Element();
272             for ( [b]pElemParam[/b]; pElemParam; pElemParam = pElemParam->NextSiblingElement( "param" )) {
273                if (pElemParam->FirstChild()->Type() == TiXmlNode::TEXT) {
274                     params[pElemParam->Attribute("name")] = pElemParam->FirstChild()->Value();
275                }
276             }
277             cout << "Amplitude: " << params["amplitude"] << endl;
278         }
I am using TinyXML and this code loops over children. When I run my program, I get "Amplitude: 1" so clearly the program reads the XML file, and enters the for loops even though the statements apparently have no effect.

Any ideas? Is this a bug in g++?
I've bolded the bits that are causing the warnings.

pElem and pElemParam are already declared, so those statements do nothing. You could either move the initialisation:
code:
267         for (pElem = hRoot.FirstChild( "input" ).Element();
268              pElem;
                 pElem = pElem->NextSiblingElement("input")) {
269             params.clear();
Or make it explicit you're not using that section of the statement:
code:
267         pElem = hRoot.FirstChild( "input" ).Element();
268         for( /***/; pElem; pElem = pElem->NextSiblingElement("input")) {
269             params.clear();
The /***/ above isn't needed, but is it good practice to draw attention to the fact that you're not using that section in the usual manner.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply