Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The reason it isn't working is because the condition in the if: statement is incorrect. When you write

    if first == "a" or "e" or "i" or "o" or "u": 

... what it is really saying is

        if (first == "a") or ("e") or ("i") or ("o") or ("u"):

That is to say, it only compares the value of first to "a"; the rest of the clauses all evaluate to True, so the the whole condition will always be True.

In order to compare a single value against several values, you need to use a list and a set membership (in or not in) operator:

    if first in ["a", "e", "i", "o", "u"]:

Note that you also aren't handling the case of uppercase values, but that's a complication you can handle on your own, I think.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

OK, then. Well, as a beginner, I'd like to offer a quick lesson on the importance of suitable indentation:

#include <iostream>

using namespace std;

int main()
{
    int p = 1, i = 1, j = 2, M;
    float t = 1 / 2;

    cout << "give M: ";
    cin >> M;
    for (i = 1; i <= M; i++)
    {
        p *= t;
        i += j;
        j += i;
        t = i / j;
    }

    cout << "Produkt is: " << p ;

    return 0;
}

While this may look peculiar at first, you'll find that it is much more readable this way.

Now, then, did you pick one of the compilers I linked to, and were you able to try it? Or did you need more help?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Just how you would do that would depend on the compiler, and possibly on the development environment you are using as well. Do you have a compiler chosen already, or are you looking to get one? If you have a compiler already, do you have an editor or Integrated Development Environment (IDE) in mind to use with it?

If not, have you looked into either Visual C++ Express (which comes with a built-in IDE called Visual Studio Express) or the Gnu Compiler Collection (which is mainly command-line driven, but can be used with IDEs such as Code::Blocks or Eclipse)?

Can you tell us something of what you are trying to do? By that I mean, are you compiling a specific program, or are you learning to program and need help getting started? The more you can tell us about what you need, the more specific we can be.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

There really isn't any one language which all beginners start with, and no language appeals to everyone; the real issue is that a lot of universities start people off with C (or worse, C++), despite it being poorly suited for most beginners.

As for complexity, C is actually a rather simple language, compared to Python. This is not the same as saying it is an easy language by any stretch of the imagination. C is simple in the same way chess is simple: it has relatively few rules and very few exceptions to those. It still takes years to master either of them, and starting of with them before any others is, for most people, an exercise in frustration.

(To follow the analogy, Scheme and the other Lisp languages are like go: there are hardly any rules to the game at all, and learning how to play takes just a few hours, but mastery is a lifetime's work. Conversely, C++, Java and Perl are like Brockian Ultra Cricket or Dragon Poker - mountains of rules and variations thereof, more than any one person could ever really learn. But that's still better than C# and VB.Net, which are like TEGWAR - the rules seem to slip and slide around at random and no one will tell you all of them, and eventually you end up under the table with a massive headache.)

Python is more like, say, your typical video game. It has …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

BTW, why did you choose to copy someone else's post from 2 years ago, from a completely different forum, and give only part of the necessary details? It strikes me as odd, to say the least.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Well, for a design document, I suppose it's a start. You would need a lot more detail, however, even before you could consider writing any actual code.

If your actual goal is to write a photo editing program, well, that's about as complex as any project you could have chosen. I think I personally would tackle just about anything else first before trying something that difficult... and I do systems programming as a hobby.

BTW, despite this book's title and the opinions of far too many 'educators', neither C nor C++ make a good language for beginners; they are both designed for experienced, professional coders, especially C, and they both are far too difficult for most newcomers. I would recommend a language like Python or Ruby as a better place to start, though that is a personal opinion and completely subjective (actually, I would really recommend Scheme, but there you're getting a bit too outré for most people).

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Well, what you have to understand is that the braces aren't directly connected with the loop or conditional, per se; in fact, the control structures are actually defined as to accept the one statement immediately following the conditional. In EBNF, it would be defined as:

<if-statement> ::= 'if' '(' <conditional> ')' <statement>

For those unfamiliar with EBFN, what this says is, "an if-statement is defined as the word 'if', followed by an open parenthesis, followed by a conditional, followed by a close paqrenthesis, followed by a statement". Note that this

What the braces are used for is to form a compound statement or block which can be placed anywhere there could be a single statement. Indeed, in the formal definiton, a statement is defined in terms of either simple-statements or blocks. Again, in EBNF, you would have:

<statement> ::= <simple-statement> ';'
               | <block>

<block> ::= '{' <statement>* '}'

What the first says is, "A statement is defined as either a simple-statement followed by a semi-colon, or a block.", while the second says, "A block is defined as an open brace, followed by one or more staatements, followed by a close brace". You'll notice two things: one, that you can put a block anywhere you can put a statement, and two, that the definitions are mutually recursive, that is to say, they are defined in tems of each other. This recursive expansion is part of what makes complex compound statements possible.

If this is still …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I'm afraid we'll need more information than just the assignment statement. Is there anything in particular that confuses you?

  • Do you know how to use multiple source and header files?
  • Do you know what a pointer is, and how to use one?
  • Do you know how to define a class, and where you would define it?
  • Do you know what a member (or instance) variable is, and how to declare one?
  • Do you know what a member function (also called an instance method) is, and how to define and implement one? Do you know where you should implement them?
  • Do you know what accessors and mutators (i.e., getters and setters) are, and how to implement them?
  • Do you know what a queue is, and how to define and implement a class that acts as one?
iamthwee commented: solid advice +14
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Oh, I see. Oh dear me.

OK, then, I will start with the if() statement, as it is the easier of the two to understand. Basically, what an if() statement does is take a true or false value, and based on that value, select from one of two paths to take. The general form of it is

if (<conditional_expression>) 
    <true_case>
else
    <false_case>

In the case where you only need to test for a true case, you can omit the else and the false case.

This particular if() statement has two parts, connected by an AND operator (the && part). This means that the condition is true if and only if both of the clauses on the two sides of the operation are true.

The first part tests whether a given character is a digit, that is, whether the character value is a '0', or a '1', or a '2', and so on through '9'. The isdigit() function (technically a macro in most implementations, but that's not important here) is a standard library routine that does this test. The second part of the condition checks (somewhat redundantly, as it happens) whether it the given character is not equal to the NUL character, that is, a character which is encoded as the number zero (which is not the same as the character '0', BTW; see the ASCII table for a quick review of the character encoding values). If both of these are true, then it performs the next …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Well, the good news is, a certain number of C++0x/C++11 features did make it into VS2010 and VS2012; the bas news is, constexprs weren't among them. A detailed explanation of which features are and aren't supported can be found here.

This leaves you with the prospect of using a different compiler with Visual Studio, something that is possible with the full version of VS but not the Express versions. The obvious choice for this would be GCC, which has a little better support for C++11 than the Microsoft compilers do, but getting it to work with VS is not easy; if you really wanted to use GCC, it would make more sense to ditch Visual Studio entirely in favor of something like Code::Blocks or Eclipse, either of which integrate much better with GCC. Since your main goal appears to be to use Visual Studio Express 2010, this probably isn't an option.

The Intel C++ compiler may be an option, but it is quite expensive (US$1500), and again, you would need the full version of VS2010 to support it.

A comparison of different compilers support for C++11 can be found here. As you can see, support for the new features is spotty at best, with all of the current compilers.

As for incremental linking, I don't know of any way to disable that in VC++ Express. Is there any particular reason you need to disable it?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

First off, in the future, when asking a question, please post a new thread of your own rather than resurrecting one from five years ago.

Second off, the real question here is, what sort of hash function should you use? The fairly simple approach you mention (taking the modulo of the key by the length of the table) has obvious flaws if the keys aren't evenly spaced. Since you need to map the keys to exactly 33 slots, with exactly three slots per index, finding the appropriate hash function is not simple. However, if you know all the keys ahead of time, it would simplify the matter tremendously, because then you could apply the technique known as perfect hashing to generate the hashing function itself.

Unfortunately, most perfect hashing approaches are predicated on their being no collisions, that is, that there are exactly n indexes for n keys; it is mainly useful when the number keys is relatively small compared to the potential key space. Since you haven't told us what the keys are, we can only guess as to the nature of the keys or the size of the key space, though given your original hashing function it sounds as if they are numeric values of some sort.

It may be possible to treat the 33 slots as 33 indices, if you treat the hash as a two-part value mapping to the index of the table and the indices of the arrays, but that would restrict the …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

More to the point, the original post was over a month ago; presumably, the project was due already. In any case, it is unlikely that the 'bar code' the OP was reading was in a standard format, given the representation of the bar code as bars and colons.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

OK, I'm puzzled about that myself, but not for the same reason. At this point in the function, the variable temperaturef doesn't have any set value, which means it should be giving a NameError exception instead, like this:

NameError: name 'temperaturef' is not defined

Instead, it is acting as if the temperaturef used in the top-level code has already been set to a float value, as it is on line 52. This shouldn't be in scope inside of display_temp().

Now, if we assume that temperaturef is in scope for some reason, then it makes sense. The __getitem__() special method is the function used in collection classes to overload index operator '[]'. By having the [0] folliwing temperaturef, you are in effect trying to treat the variable as if it were a collection variable, which it isn't.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I was hoping to coax the OP into solving the issue, or at the very least go over the specific problems it had with us explicitly, but oh well.

If it helps any (which I doubt, but who knows), here is how I would solve this problem:

#include <iostream>

struct TaxRate
{
    int bracket;
    double rate;
};


int main()
{
    float income = 0;
    float tax = 0;


    const TaxRate tr[6] = {
        {0, 0.0},
        {10000, 0.1},
        {30000, 0.2},
        {50000, 0.3},
        {70000, 0.4},
        {100000, 0.5}};

    std::cout << "Enter income: ";
    std::cin >> income;

    if (income > tr[5].bracket)
    {
        tax = income * tr[5].rate;
    }
    else
    {
        for (int i = 5; i > 0; i--)
        {
            if (income > tr[i-1].bracket && income <= tr[i].bracket)
            {
                tax = income * tr[i-1].rate;
                break;
            }
        }
    }

    std::cout << "Income tax is :" << tax << std::endl;

    return 0;
}

Since you're course probably hasn't covered arrays and structs yet, and might not even have covered loops yet for all I know, this isn't going to help you in your particular assignment, but it might give you some idea of how to solve it in a bit more professional manner.

ddanbe commented: Nice code +14
sujanthi.kumari commented: thanks +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

In what way isn't it working? Does it fail to compile? Do you get any error or warning messages? Does it run and crash? Does it give the wrong values? We really need more details in your initial post in order to help you.

BTW, two things you should know. First off, the <conio.h> header is non-standard, and specific to certain MS-DOS and Windows compilers. You would be better off avoiding it entirely. Second, the <iostream.h> header is an obsolete form; the C++98 standard redefined all the standard headers to remove the '.h' extension, and add a 'c' to the beginning of the older C library headers. For compilers released after 1999, you should always use <iostream>, and similarly, use headers such as <cstdlib> instead of <stdlib.h>. Just something to be aware of. You also need to scope the standard library functions and classes as being in the std namespace, so you need to either add using namespace std; to the beginning of your program, or else explicitly scope them using std:: - for example, you would have std::cout instead of just cout.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Standard, no, but it is freely available and appears to be reasonably well documented. Unfortunately, I'm short on time right now, or else I would dig into it a bit deeper; as it is, I'll try to get back to it later tonight, if I have the opportunity (though I doubt I will).

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Part of the problem is that you are closing the output file inside the loop you are reading and writing in, which means you are no longer actually writing to the file after the first pass. But that's just the start of the problem.

The problem is that you cannot write and read a whole object in like that to and from a file and expect it to be usable that way. An object (or even a POD struct, if it contains pointers or objects) has references to specific locations in memory (e.g., the virtual functions table), and reading in the data as a bulk record won't correctly recreate the object. Just as with the display() method you wrote, you need to read each individual instance variable in seperately. In the case of the string, since that is itself an object, you need to read the string data in as a char array first, or else use the input selector (>>) rather than the read() method. Since it involved private data, you would also need it to be in a method or a friend function.

Fortunately, there is a convention for this, which is independent of whether it is a file stream or not: you can overload the input and output selectors as friend functions of the class. We can even define how to display the data with custom manipulators, though that's a fairly advanced technique.

While we're at it, let's break the program up into separate components, …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Unfortunately, Moschops is right. Assembly language by its very nature isn't particularly friendly, and x86 assembly specifically is rather gruesome. The best you can really do is get a good IDE such as RadASM, WinAsm, AsmEdit or EasyCode, which lessens the severity of it somewhat. For the sort of work you seem to be doing, AsmEdit is probably the best choice, as the others are all geared toward writing applications rather than low-level systems code.

Mind you, I am presently writing my own x86-64 assembler, but given that a) it would be using a radically different syntax based on Lisp, and b) I am unlikely to ever finish it, I don't think that it is much of an option for you.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

First off, we don't do other people's homework for them. Second, we don't do other people's homework for them. And third, we don't do other people's homework for them. Sensing a pattern here yet?

No one here will simply hand you a solution on a silver platter. If you show us what you've done, what you've tried to do, and what problems you've had with it, then we'll be happy to help. If you have specific questions, we can answer them, or at least point you in the right direction. If you have a program with a bug you can't swat on your own, we'll be glad to assist, so long as you pay attention to the forum rules and post sensible questions in an intelligent manner that we have some reasonable hope of answering.

But just cutting and pasting an assignment into a message, without even prefacing it with something like, "I have this homework problem that I can't solve...", is likely to get you booted from the message boards here and elsewhere - if you're lucky. What happens to you if you are unlucky is... well... let's just say that this guy probably won't be trying that again, on that forum or this one.

We take this issue seriously here. Very seriously. Asking us to do homework for you is a grave breach of academic ethics on your part, and actually doing so would be an even bigger breach on …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Can you be more specific? What didn't work? What was the path you were trying to use? What kind of error did it return?

ALso, can you give us the OS you are running under? The open() function you describe is primarily a Unix/Linux system call, though there are versions of it that have been ported to DOS and Windows. If you are running under the latte, there may be issues with how it handles pathnames, especially if you are using a DOS compiler (such as Turbo C) under a Windows system.

BTW, do you know why your instructor wants you to use this function? It's a rather unusual requirement, and it might shed some light on it if we knew the reason why.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I would recommend starting with BeautifulSoup, which is made for just such a purpose.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I would start by considering how the chat protocol to use, whether it is one you have designed yourself, or an existing one such as XMPP. While an existing protocol is likely to be much more elaborate than one you've worked out yourself, it would have the advantage that most of the design work is done for you, and you could test it against an existing implementation such as Jabber or Pidgin.

Still, a simpler protocol has it's advantages. It really only needs three things:

  • some sort of handshake for connecting the two clients
  • a way of transferring a message
  • a signal to disconnect the session
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I would, first off, recommend against using scanf() directly for this; since the input is by line, and of irregular size, I would instead read the data with fgets() and then apply sscanf() to the string after it has been read in. This should avoid the issue nicely, as you need only check to see if there is more data in the string on each pass of the loop, rather than having to check for a specific marker.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Oh dear, not this argument again :( It seems as if this argument flares up every three months or so, and frankly, it is purely a waste of effort.

Let's first define our terms: a programming language is a language is capable of describing a sequence of actions for a computer to take, either explicitly (as in procedural or OOP languages) or implicitly (as in functional or logic languages). A script is a program which is primarily used for controlling the invocation of othe rprograms. A scripting language is a programming language used primarily for writing scripts.

Note tha there are two crucial facts here: first, that scripting languages are programming languages, and second, that by this definition, Python and Ruby are not scripting languages. While they can be used for writing scripts, and often are, neither are used exclusively for scripting (even Perl, which is mostly used for scripting, is entirely a scripting language). This leaves the rather bogus term 'scripting language' for those languages which really are used exclusively for scripting, such as the various shell script languages, or Windows batch scripts.

Octet commented: A Good Summary, and I am going to agree and step out of the discussion now. +5
sepp2k commented: Well said. +5
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

OK, perhaps we need to start over from scratch. What you need to understand is that an object is a model of something. It can be something real, like a car or a person, or something conceptual, like a list or a dictionary (I use those examples because, as it happens, lists and dictionaries are objects in Python). The point is that the object captures or encapsulates the properties of the thing it is modeling, its current state, and its potential behavior. The properties and state are described by variables that are part of the object, called instance variables, and the behavior is described by functions which are bound to the object, called instance methods.

A class is a description of an object, a sort of template or mold for making new objects. It defines both the instance variables of the object, and the methods the object can perform. It works by providing a way of creating a new object - the __init__() method, also known as the constructor or c'tor. The c'tor primary job is to set the initial values of the object's instance variables. It can do anything that you can do in any other method, but it should initialize the instance variables in some way.

In Python the first argument of any instance method is the object itself, which by convention is named self. This is true of the __init__() method as well, even though it is actually not an instance method per se (it is a …

Necrozze commented: Thanks man! This was exactly what I was looking for +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

usy1010: First off, you should never hijack an existing thread with an unrelated question. It is better to start a thread of your own.

More importantly, to both you and the OP, you have to understand that DaniWeb is NOT a free-homework-solving service. Simply posting a question as you both have done, without showing that you've made some effort to solve the problem, is a violation of the DaniWeb forum rules and the Terms of Service. If you have a problem with your own code, fine, we can give advice; but you have to show us your work. We are here to help you learn; We are not here to help you cheat.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Aside from the linkage problem, I noticed that in the InitialiseTree() function, you have several places where you are using 2^x to exponentiate the powers of two. The problem with this is that C doesn't have an exponentiation operator; the caret (^) is used for the exclusive-or operator instead. To exponentiate, you need to #include <math.h> and use the pow() function from the standard library, like so: pow(2, 0).

Also, you can significantly simplify that function by placing the repeated computations into loops, and moving the larger set of calculations to a utility function, like so:

void InitialiseTree(FILE *wordlist, typosWords W, int totalwordsin)
{
    int i=0, j, res;
    char word[20];
    struct timeval start, t[7], tALL;

    gettimeofday(&start, NULL);    /* start timer */
    do{
        res=fscanf(wordlist,"%20s\n", word);
        InsertWord(W, word);
        i++;
        for (j = 0; j < 7; j++)
        {
            if (i == (1024 * (int) (floor(pow(2, j)))))
                gettimeofday(&t[j], NULL);    /* save time */
        }
    }while(res!=EOF);

    totalwordsin=i;
    gettimeofday(&tALL, NULL);          /* save total time */

    for (j = 0; j < 7; j++)
    {
        calcElapsedTime(W, &start, &t[j], j);
    }

    calcElapsedTime(W, &start, &tALL, 7);
}


void calcElapsedTime(typosWords W, struct timeval* start, struct timeval* t, int offset)
{
    double elapsedTime;

    /* calculating time for all words to be inserted */
    elapsedTime = (t->tv_sec - start->tv_sec) * 1000.0;      /* sec to ms */
    elapsedTime += (t->tv_usec - start->tv_usec) / 1000.0;   /* us to ms */
    SetInsertTime(W, elapsedTime, offset);
}

This makes the function much easier to understand, and should make fixing and maintaining the code much …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I believe I see where the problem lies. The local variable ylop is defined in main.c, inside the main() function, as a regular char variable. The problem is that the functions are being selected using conditional compilation, which is performed by the pre-processor, not the compiler per se.

The thing is, the preprocessor #if directive knows nothing of C language variables; it can only operate on those constants which are defined using the preprocessor itself. The preprocessor operates entirely at (or, to be strictly accurate, before) compile time, and run time variables cannot affect it. Using conditional compilation to set something at run time simply won't work.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Technically, the while() loop is what is known as an 'indefinite iteration', which is to say that it repeats the body of the loop zero or more times, with the number of repetitions being unknown at the time the loop is begun. It repeats based on a condition which holds true, and stops repeating when the condition no longer holds. The form of the while() loop in EBNF looks like this:

while-loop ::= 'while' '(' <condition> ')' <body>

body ::= <statement>
       | '{ <statement>+ '}'

I doubt that this is any less confusing, however. The practical upshot of this is that the while loop has a conditional, similar to an if() statement, except that instead of selecting the body that follows it once it repeats until something changes the condition to false. So, let's say you want to read in something from the console, and keep repeating echoing back a line number and the string until it gets to an end-of-file marker (Ctrl-Z in Windows, Ctrl-D in Unix) is found, then you would write something like this:

#include <iostream>
#include <iomanip>
#include <string>

int main()
{
    int count;

    while (!std::cin.eof())
    {
        std::string line;
        std::getline(std::cin, line);
        std::cout << std::setw(4) << count << ": " << line << std::endl;
        count++;
    }

    return 0;
}

Now, you may wonder what the point of this program is, as it doesn't seem to be very useful; but this is actually a rather neat little utility of a type called …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Oh, yes, if course, my apologies for that slip.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

First off, you have to understand that no one here is going to write the program for you. This forum is for assisting programmers with projects, but we do not provide free homework solutions of the sort you seem to be looking for. In the forum rules, it states specifically:

Do provide evidence of having done some work yourself if posting questions from school or work assignments.

This means that, unless and until you show us the code you've already written, we cannot do much to help.

Second off, is the program supposed to be in C, or in C++? These are two different languages, even though they are closely related, and writing the program for one of them is different from writing it for the other.

Third, if you don't know how to write the program, can you tell us what is holding you back, specifically? We may be able to give general advice, even if we can't solve it for you directly.

Fourth, you need to realize that this forum is not like chat or IM; there may be a lag of hours or even days before you get a response. Conversely, the size of the message does not have to be limited; thus you can and should write out full setneces, without resorting to SMS-type abbreviatations.

ddanbe commented: Your English and comment are better! +14
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

As PyTony points out, the code as given does not use the zipfile module, but rather calls on a separate program named 'zip' to perform the file operations. That is both unnecessary and non-portable. This is how it would work using the zipfile module:

import zipfile

zip = zipfile.ZipFile(target, 'w')

Now, to get the desired effect of zipping up a whole directory tree, you'd have to recurse through the whole directory tree and add each file in turn. However, if you have Python 2.7 or later, you can use the make_archive method of the shutil module instead:

import shutil

# where we are running in the root directory of the archive,
# and source is the archive's base directory 
make_archive(target, 'zip', '.', source)
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

First off, since you are manipulating them together, it may be a good idea to bundle the array and max together, along with the current size:

struct people
{
    struct person** data;
    int size, max;
};

It is almost always better to separate the functions which manipulate data from the input and output functions, so I would keep view() and del() separate. Similarly, I would separate the add() and del() functions from the function to resize the array, as so:

struct person** resize(struct people p, int new_max)
{
    p->data = realloc(p->data, new_max * sizeof(struct person));
    p->max = new_max;

    return p->data;
}

struct person* add(struct people p, char* firstname, char* lastname, char* birthdate)
{
    struct* person new_person;

    p->size++;

    if (p->size >= p->max)
    {
        // if the current size is equal to or greater than
        // the total size of the array, double the size of the array
        result = resize(p, p->max * 2);
        if (result == NULL)
        {
            return NULL;  // could not allocate additional space
        }
    }

    new_person = p->data[size - 1];
    new_person->firstname = firstname;
    new_person->lastname = lastname;
    new_person->birthdate = birthdate;

    return new_person;
}

This approach is not only more efficient than resizing every time the size changes, it separates the three sets of concerns (inputting the new person, adding the new person to the array, and managing the size of the array) so as to make it more modular and easier to understand.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The origina; post was from two months ago; it is safe to say that the 48 hour deadline has long since passed. :-p

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

You sholdn't need to; it is part of the standard Python library. I gather you were unable to use it? What version of Python are you using? What exactly happens if you enter the following into the Python interpreter prompt?

import random

random.randint(0, 6)
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

First off, let's get this code suitably indented, so that it is readable:

#include <stdio.h>

int main()
{
    write(1,"salam",5);
    char a[2];
    char b[5];
    read(0,a,2);

    if(a[0]=='8')
    {
        write(1,"ok",2);
        read(0,b,5);
        write(1,"ok2",3);
    }
    return 0;
}

I know that for newcomers, this may make it look like modernist poetry of some sort, and the benefits may not be entirely obvious. Trust me, however, when I tell you that indented code is vastly easier to read, understand, and most importantly maintain than unindented code. The specific indent style you choose is less important than applying some sort of indentation, and being consistent with it.

Now, with that out of the way, we can look at the program sensibly. Looking at the code, the only problem I really see is that you don't have the correct header (read() and write() are low-level functions declared in <unistd.h>, not <stdio.h>), and that you don't have any newlines. If you look at the output again, you'll see that the second write() call does output, but that because there is no newline, it is on the same line as the shell prompt, making it harder to notice.

Now, you'll also note that both outputs are taking place on the same line, after both of the inputs. This is because when you enter a two-character sequence and hit enter, you are actually entering three characters: the '8', the 'a', and the newline. Since you only read two characters out of the buffer, the newline is still …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The answer to that is going to be entirely implementation-dependent, and the difference is probably negligible. Only by profiling can you get a definitive answer. The main cause of the difference probably will not be from the return per se, but from the need to pack and unpack the struct with the data.

If you don't mind me asking, why is this a significant concern? Worrying about this seems like premature optimization to me. It is generally more profitable to get the program working first, then look into the efficency of the different parts - and only to optimize those areas which can be empirically shown (via profiling) to be bottlenecks or hot-spots. Otherwise, you risk creating what Michael Abrash referred to as a 'fast slow program' - on which is nominally 'optimized', but doesn't run any better than the unoptimized version, because the worng parts of the code were tightened up at the expense of overall performance.

From a design and maintainability standpoint, it would probably be more fruitful to look at what you are doing with the data both before and after the function. If you find yourself using the structure anyway, or if the data is being passed around as a unit to more than one function, then by all means you would be better off with the struct. OTOH, if this is the only place where you use the structure, and it is used solely to pass back multiple values and not used in …

mike_2000_17 commented: Agreed +14
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

First off, please do not post new requests into old threads like this. This thread was originally posted more than half a decade ago; some of the details are now out of data (though fortunately the jist of it hasn't changed), and if nothing else it is problematic if you are adding new questions to solved threads. Please create new threads of your own in the future.

As for the question, the basic answer is the same: you can use any text editor of your choice to write the code in. Assuming you are using Ubuntu Linux, and specifically the latest version, you would again probably use gedit (which is technically a GNOME program, but can be run under Unity as well), though you are free to use any editor that produces unformatted text documents.

For assembling the PIC code, there is a full suite of GNU utilities for this, but I don't personally know much about them.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The easiest solution for this is to use a vector of vectors and let the library do the heavy lifting, but I assume that that isn't available to you for this assignment. If that is the case, then I'll walk you through what you'd need to do here. Declaring the array, which in this case amounts to a pointer to the underlying type, is pretty straightforward:

double *matrix;     // or `int matrix[];`

This by itself doesn't get you very far, needless to say. In order to allocate the array, you would have to allocate enough space for the rows times columns elements:

matrix = new double[rows * cols];

Now, it's important to keep track of the rows and columns, because the compiler doen't know that the block of data you just allocated is a 2D array; thus, you will probably want to wrap the array into a class:

class Matrix  
{
private:
    double data[];
    unsigned int rows, cols;

public:
    Matrix(unsigned int r, unsigned int c): data(0), rows(r), cols(c);

    double operator()(int x, int y);
};

// this would go in the implementation file
Matrix::Matrix(unsigned int r, unsigned int c)
{
    int size = rows * cols;

    data = new double[size];

    // initialize the data to zero
    for (int i = 0; i < size; i++)
    {
        data[i] = 0.0;
    }
};

double Matrix::operator()(unsigned int x, unsigned int y)
{
    if (x > rows || y > cols)
    {
        throw MatrixIndexException();  // you'll need to define this …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Valid point. Looking again at the page I'd linked to, I see I was clearly mistaken. I think I was jumping to a conclusion that the mridul.ahuja was talking about Turbo C, and went off half-cocked as a result. Also, it is so common to see 32-bit ints these days that is is easy to forget that they are non-portable.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

If you need to store large values (above 32,767 or below -32,767), use long.

Actually, this range only applies to 16-bit compilers such as Turbo C. Pretty much all modern C compilers for Windows, Linux and MacOS use a 32-bit int, in which case the range of values will be from -2,147,483,647 to 2,147,483,647. This is equal to the long value on most 16-bit compilers, and many 32-bit compilers for that matter. Depending on the compiler, a long may be 32-bit or larger, while (in C99 and later) a long long is at least 64 bits wide. A short is defined as being at least 16-bits wide and less than 32-bits wide, with 16-bits being typical.

This brings up an important point, however. The C language standards (at least up to C99 - I don't know about C11), the sizes for the standard integer types are not specified, because the language runs on som many different platforms that it is impossible to set a fixed size for them. While almost all modern processors are either 8-bit, 16-bit, 32-bit, or 64-bit - with 32 and 64 being almost universal for desktop systems after the mid-1990s, and 8- and 16-bit common to many embedded systems - there are exceptions, and the language standard has to allow for these edge cases. The actual specifications can be found here.

To deal with exact sizes, the C99 and later standards added the <stdint.h> header, which defines several exact-sized types in both …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Basically, you would need to call the interrupt twice, once for each string you are printing.

SECTION .text
            global _start
_start:
            mov eax, 4          ;sys_write
            mov ebx, 1          ;output to screen
            mov ecx, string     ;creates address for my string variable
            mov edx, length     ;creates address for my length variable
            int 80h             ;call the kernel
            mov eax, 4          ;sys_write
            mov ebx, 1          ;output to screen           
            mov ecx, string2    ;creates address for another string
            mov edx, length2    ;creates address for another length
            int 80h             ;call the kernel
            mov eax, 1          ;sys_exit
            mov ebx, 0          ;no error exit
            int 80h             ;call the kernel

SECTION .data
string: db 'Howdy Folks!', 0Ah  ;output string
length: equ 13                      ;length of string
string2: db 'Another line!', 0Ah    ;output another string
length2: equ 14                 ;length of string2

Note that the code as given had a number of problems with it; for example, the entry point should have been _start, not START (otherwise the standard Linux linker, ld, won't find it), and the lengths of the strings should have included the newlines.

As for what int 80h does, it signals a software interrupt, a low-level mechanism used to send requests to the kernel. When an interrupt occurs, whether from the hardware or from a program, the current program is halted and the system goes into a kernel routine mapped out to handle the interrupt. The interrupt mapped for hex 80 (decimal 128) happend to be mapped to a set of operating system services which get selected from a …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

It would depend on just what you are doing, but generally speaking, you would have them in separate files. Keep in mind that you can only have a single public class in a file.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

NASM probably is your best bet, then; it shouldn't be difficult to get it to work with Code::Blocks. You can get the Windows installer from here.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Deceptikon: Point taken.

Labdabeta: I personally prefer NASM, but the one that comes with the GNU Compiler Collection (and hence is the default for Code::Blocks and FSF packages in general) is GAS. The problem with GAS is that it uses a notation based on the older AT&T UNIX assemblers, and which is radically different from the Intel-style assemblers such as MASM and NASM. A good overview of the diferences between the two syntaces can be found on the OSDev wiki. While it isn't too difficult to get used to AT&T style, most Windows programmers are more familiar with the Intel format.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Did the assembler simply copy-paste the library code in (like a header file in c/c++)

If it was a statically linked library, yes.

Er, not exactly. The library code is not in the form of source code, but rather is a binary file containing the compiled or assembled code in what is known an 'object format' (which has nothing to with object-oriented programming). The object format (which under Windows is one called PE) contains machine code, except that the references to specific addresses are stubbed out, as well as the symbol information needed by the linker and loader to patch the addresses into place once the program is run.

When the program is linked to the library (a step which most modern IDEs do automatically, but which historically was a completely separate step from compiling), the object code sections for the specific library routines are extracted and patched into the program to form the executable file. The linker resolves the calls in the program to match the linked-in library code.

Now, the executable file is still not pure machine code, because the specific addresses for jumps and so forth still haven't been resolved; doing that is the job of the loader, which is the part of the operating system that loads the program into memory. The addresses cannot be resolved until run time, because the system can (and will) load the code into different locations in memory, even with each process getting it's own virtual memory …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

According to your personal profile, you are runing Windows 7, which means you are running an x86 processor, either a 32-bit system or (more likely, if it is running 7) a 64-bit 'long' mode system. There are several assemblers for Windows - Macro Assembler (MASM), Gnu Assembler (GAS), and Netwide Assembler (NASM) being the most common - so it would depend on which one you are using.

(Unless you are using an emulator such as SPIM or PEP-8, in which case you are looking at whatever assembler comes with the simulator. The same applied to pseudo-machines such as the JVM or the .NET Common Language Runtime.)

As for the diassemblies, if they are for a Windows native code, then there should in fact be library calls. In x86 assembly, these would take the form of either a CALL instruction for the standard libraries, or if you are invoking a Windows system call directly, a SYSENTER or a task gate (IIRC). However, there is no easy way to determine which function call is going to which external routine in a disassembly, since the source symbol tables aren't available. Disassmeblers can only infer so much without the symbols.

OTOH, if they are managed CLR code (which is what you'd get from, say, C# disassemblies), then you aren't really looking at native code at all - the 'assembly language' is that of the Microsoft Common Language Runtime, a simulated virtual machine used to simplify the compilation process and make programs more 'secure' (supposedly). …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The first one is simply a misspelling in the definition of the showKilometers() method.

The second is that you declared showFeet() ad type void, when it should in fact return a double.

On a related not, you need to have the actual return statements in the three 'show' functions:

  public static double showKilometers(double meters)
  {
    return meters * 0.001;

  }
  public static double showInches(double meters)
  {
    return meters * 39.37;

  }
  public static double showFeet(double meters)
  {
    return meters * 3.2; 
  }

HTH.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Sorry for the delay in getting to this, I missed it when it was on the front page earlier in the week.

For the first case (line 7), I am guessing that the problem is that the MARS assembler doesn't support adding two immediate sub-values. The simple solution is to do it as a single constant:

    li    $a0, 500004

For the two cases (lines 94 and 289) and where you are using SRL, you want to use SRLV instead; SRL works with an immediate value for the shift amount, whereas SRLV (Shift Right Logical Variable) takes a register value. I'm not sure why this worked on QtSPIM, as it isn't correct to begin with.

Conversely, on line 97, you are using an immediate value with AND, when it should be ANDI. Unfortunately, that shouldn't work either, as the value is too large for an immediate; you would need to do this:

    li    $t3, 0xfffffffc
    and   $t2, $t2, $t3

Unfortunately, since LI is actually a two-instruction macro, this means that it takes three instructions instead of one. Still, it's not too bad a cost. If you really need to save one cycle at that point, you could do this instead:

    addiu $t3, $zero, -3
    and   $t2, $t2, $t3

... but frankly, I wouldn't bother.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Unfortunately, there is no real answer other than to read the file contents after the point of insertion, and re-write them with an offset equal to the size of the text you are inserting (one byte, in this case). Given the size of the file, it may be easier to simply read the whole text beyond the insertion point into memory, do the insertion, and write it all back.

Can you tell us something of the actual goal of your program? This question has the feel of a simplified example. For more elaborate editing, you might want to read up about the 'buffer gap' technique, which is described in detail in the online textbook The Craft of Text Editing.

As for why seekp() "isn't working", in append mode, just how were you trying to use it? Keep in mind that seekp() sets the position for writing, but to set the position for reading, you need to use seekg().