Banfa 597 Posting Pro Featured Poster

Looks like A QTableWidget automatically deteles any cell widgets you set.

That means that for each of the 3 cell widgets you set it will try to delete the widget individually. However you did not individually allocate those widgets, you allocated an array of widgets, that means that for 1 entry it will delete all three widgets where as for the other 2 it will try to delete a pointer that is not valid.

You need to allocate (call new) separately for each widget you wish to add to the table.

Banfa 597 Posting Pro Featured Poster

I imagine this is an endian issue. When storing an integer in memory little endian processors store least significant byte first, big endian processors store most significant byte first.

So the numbers are stored in memory as follows

30030 
little endian machine: 4E 75 00 00
big endian machine:    00 00 75 4E

34094
little endian machine: 2E 85 00 00
big endian machine:    00 00 85 2E

Taking -16 to mean second one bigger and 1 to mean first one bigger and remembering that memcmp compares a byte at a time then.

On a little endian, Linux, it compares
1st Byte: 4E with 2E; they are different, 4E is bigger so the first parameter is bigger so it returns 1 and stops.

On big endian, HP, it compares:
1st Byte: 00 with 00, the same continue to 2nd byte
2nd Byte: 00 with 00, the same continue to 3rd byte
3rd Byte: 75 with 85; they are different, 75 is smaller so return negative. It is doing the comparison by subtraction and returning the result if it is not 0, 0x75 - 0x85 = -16

That is how you get different results on different machines with them both being correct.

Banfa 597 Posting Pro Featured Poster

The bar only seems to be appearing when you are looking at a thread, for me it disappears when I am looking at a forum thread list which is a fairly ittitating feature in a navigation bar.

Banfa 597 Posting Pro Featured Poster

[condition] ? [statement1] : [statement2];

Strictly it is

[expression1] ? [expression2] : [expression3];

There are no such things as conditions in C only expressions and statements. Statements are not required to return a value but expressions are.

expression2 is evaluated if expression1 evaulates to true (any non-zero number) otherwise expression3 is evaluated. The value of the evaluated expressions (either 2 or 3) is returned.

Generally expression2 and expression3 must evaluate to the same type or you are likely to get warnings or errors from your compiler.

Banfa 597 Posting Pro Featured Poster

Correct C#Jaap, the logical and (&&) and or (||) operators use shortcut evaluation, that is if they can determin the result after evaluating the left hand expression they do not bother evaulating the right hand expression. For && this means if the left hand expression is false the right hand expression is not evaluated and for || this means if the left hand expression is true the right hand expression is not evaluated.

It means things like you can safely test a pointer and dereference it in the same if statement

if (valid != 0 && (*valid) != 0)
{
  // Its valid
}
else
{
  // Its not valid or valid is NULL which is also probably not valid
}   
Banfa 597 Posting Pro Featured Poster

strlen and sizeof should always return different values because strlen never includes the trailing '\0'. In a compleatly normal string such as "Hello World" with no embedded terminators strlen will return a value 1 less than sizeof returns.

It they don't return different values you have a buffer overrun in progress.

Banfa 597 Posting Pro Featured Poster

Thats because line 59 is the first time in the file that the identifier sortVecByCreditsAscending is mentioned so as far as the compiler is concerned it is undeclared, hence the error.

Line 61 and 62 are wrong, 61 declares a function and 62 returns from main, not what you intended. The cmp function from your first code listing does what you want, I would reinstate that and then change line 59 to

std::sort(userData.begin(), userData.end(), cmp);
Banfa 597 Posting Pro Featured Poster

You never allocate any memory for layout, you are dereferencing and invalid pointer.

Banfa 597 Posting Pro Featured Poster

Basicall you can't do what you are trying to do at line 8. You can not compare a value to an array of values, you have to do the comparison individually, or in this case have a string containing your hexadecimal characters and use a string search function (such as strchr) to see if your entered character is contained in that string.

Banfa 597 Posting Pro Featured Poster

To start with scanf("%s",&sh); is incorrect it should be scanf("%s",sh); because sh is an array so using it without any [] already produces a pointer to it, you don't need to de-reference it.

Secondly, never, ever use gets, always use fgets, so not gets(sh); but fgets(sh, sizeof sh, stdin); it is safer since you can't overwrite the buffer, but note that gets does not return the '\n' at the end of the line and fgets does.

So the problem is mixing scanf and gets. gets reads up to the first '\n' character in the stream, scanf reads a data to fit the provided format string, skipping white space. So when you make this call scanf("%d",& cont_flag); it leaves a '\n' in the stream since you didn't tell it to read it in any way and the following call to gets reads the '\n' that is left in the stream and returns immediately. When you use scanf("%s",&sh); it is not looking for '\n' characters so it just skips it as whitespace and looks for actual data.

Mixing input methods nearly always leads to confusion.

Banfa 597 Posting Pro Featured Poster

Clearly it is running since it "exited" just not in the way you intended.

Build and run in debug mode, if you are getting some sort of exception it should stop you where the code is going wrong. Alternitively step through the code in the debugger so you can locate by hand where it fails.

Banfa 597 Posting Pro Featured Poster

Line 41 to 45, since you don't change d, e or phi in the loop and since d is always 1 the value of s is constant with-in the loop and if e % phi is not equal to 1 the loop will never exit.

Banfa 597 Posting Pro Featured Poster

This is all platform dependent, that is different platforms may do different things, however, the "hello world" would not be stored in the read-only code segment, it is data not code so most likely it would be stored in the read-only data segment. The initial value for foo, 1, would also be stored in the read-only data segment.

The size of the data segment where foo is stored will be in the executable image somewhere so that the memory can be allocated as the program starts.

Both bar and num are on the stack (on implementations that use a stack) memory will be reserved for them in the stack frame created when main is called, this size is stored in the program code.

Banfa 597 Posting Pro Featured Poster
    typedef int (*HIG) (int,int);

In this statement HIG is the name of the new type, the type it is defined to is int (*)(int,int). This statement is defining a type that is a point to a function that returns int and takes 2 integers as parameters, as always the syntax for creating a typedef is exactly the same as the syntax for declaring a variable of that type, that is

    int (*fnPtr) (int,int);

and

    typedef int (*HIG) (int,int);
    HIG fnPtr;

are functionally equivilent, they both create a variable, fnPtr, with a type of int (*) (int,int).

You can't use sizeof in #if because #if is evaluated completely by the preprocessor (which runs first) but sizeof is evaluated by the compiler (which runs second).

However you can use sizeof in #define because the processors evaluation of #define is to set-up a text substitution so it you have a definition like this

    #define SIZE(x) (sizeof(x))

the proprocess replaces every occurance of SIZE it finds in the code with what is in the rest of the macro definition (sizeof in this case) with out actually evaluating the new text it has inserted. The compiler comes along later and evaulates the code so the compiler never sees the SIZE but does see and evaluate the sizeof.

Banfa 597 Posting Pro Featured Poster

At line 12 of you code where you create the new node there seems to have been nothing done to check that the value produced is a valid index for the tileMap array.

For example if newParent->x == 0 then on the loop iterations where x == -1 the result will be -1 which if used at lines 16 or 21 or anywhere else tileMap s accessed seems likely to produce an out of bounds access to the tileMap array which would certainly result in the unhandled exception.

Probably the easiest way to catch the error would be to run you program in the symbolic debugger, it should trap the exception and halt allowing you to examine the code and variables at the point of the exception.

Banfa 597 Posting Pro Featured Poster

Because you return s from mkUpperCase which by the time the function has finished running points to the termintor of the string.

If you print name as well as the return from mkUppercase you can see the function actually did it's job.

mkUpperCase should store and return the input pointer.

Banfa 597 Posting Pro Featured Poster

Because you have passed the vector into insert by value. When you pass by value a new copy of the variable (whatever type it is but vector in this case) is made for the lifetime of the function and gets deleted when the function exits.

So in your code when insert is called the vector is copied, a new value is inserted into the copy and then the copy is deleted leaving the original vector unchanged.

The fix is easy, don't pass by value pass by reference (note the &)

void insert(int i, string elem, vector<string>& st){
    st.insert(st.begin()+i, elem);
}
Banfa 597 Posting Pro Featured Poster

It is not so much that there is problem with your euclid function as the fact that you don't call it in add/subtract/multiply/divide thus break OOP rule number 637

A method worth implementing is worth invoking.

Not forgetting

638: A method worth invoking is worth implementing.

and

639: No method is worth implementing twice.

:D

Banfa 597 Posting Pro Featured Poster

At line 12 in quicksort.h you attempt to call template <class Comparable> void quickSort(vector<Comparable> & arr, int left, int right) before you have declared it, you define it at line 17.

Banfa 597 Posting Pro Featured Poster

Imagine you have a data class, then you would probably just need to assign the values to something valid like 0

class Date
{
public:
    Data() :
        day(0),
        month(0),
        year(0)
    {
    }

    void read(istream& in);    // Read function taking stream to read from
    void write(ostream& out);  // Write function taking stream to write to

    string getMonthString();  // Convert the month integer to a string January Feb etc

private:
    int day;
    int month;
    int year;
};

.

int main()
{
   try
   {
       Date date;

       date.read(cin);
       data.write(cout);
   }
   catch ... write catch blocks here
}
Banfa 597 Posting Pro Featured Poster

To start with the reason you have to use classes for a program that you could just write in main is so that you get used to classes. While you are studying all of you exercises are contived and often fairly small you do them to learn the techniques that you will need once you get into the real world and start working on applications with 10,000s of lines of code. But it is easier to explorer and understand the techniques on small example classes/examples.

I would have thought you would want a data class that had 2 methods (in addition to a default constructor), 1 method to read the data from standard in and 1 method to write the date to standard out. The method to read from standard in would throw your exceptions.

You can then write a main that instantiates this class and uses a try clause to encapsulate the read/write operation outputting errors when it catches an exception.

Banfa 597 Posting Pro Featured Poster

A bit of a sledgehammer approach but try calling InvalidateRect on you controls as you paint your window e.g. InvalidateRect(License, NULL, FALSE);

Banfa 597 Posting Pro Featured Poster

On entering 1111 as the input number I should get 17

I think you mean 15?

Your error is in the loop at lines 26 - 29.

For a 4 digit binary number the loop at lines 18 - 24 will c=increment i to 5, the loop in lines 26 - 29 will then run 5 times adding the values for 5 binary digits to output1, but there were only 4 binary digits. The first value you add to output1 dec[i] where i = 5 has not been set to anything and so you get a random value.

Change the loop in lines 26 - 29 to run the correct number of times (rather than the correct number of times +1) and access the correct indeces of dec. You have already solved a similar problem in the 2 loops at lines 31 and 40.

Banfa 597 Posting Pro Featured Poster

Look at the way operator++ is defined in your code at line 8; it has no class name before the method name. It is not a member of the class point but rather just a function, the only difference being it has been declared as a friend of point so that it can access the private data members of point.

Since it is a function not a method on the class you have to pass the point you are changing into the function by reference or you will get and change a temporary copy rather than the class you called the operator on.

Personally I might well make operator++ a method rather than a friend function and if I did the code would look like, I would also make it return a const ref rather than a value to help reduce copying (an issue for large classes)

class point 
{
  int a,b;
public:
  point(){};
  point(int Ia, int Ib) {a=Ia; b=Ib;}
  const point& operator++(point &p1);
};

const point& point::operator++() {
  this->a++; 
  this->b++;
  return p1;
}

However once you get to implementing binary operators, like operator+ you might well want to implement the operators as friend functions so you can implement them with the parameters both ways round i.e. point operator+(const point& p, int i); and point operator+(int i, const point& p);

Banfa 597 Posting Pro Featured Poster

I'm afraid I'm really not an expert on that module so I can only really wish you luck in experimenting.

Banfa 597 Posting Pro Featured Poster

The CMUcam2 seems to be explained at http://www.cmucam.org/projects/cmucam2/wiki where a data sheet with serial commands is available.

Banfa 597 Posting Pro Featured Poster

temp provides temporary space in which to perform the sort and should be the same size as the original array. While doing the sort the merge function uses the temp array to store the sorted list until is has complete the merge operation when it copies the sorted list back into the number array.

Using additional temporary storage in this manor is a common implementation of merge sort and would only be a problem where the size of the data set to be merged is beginning to get close to a small fraction of the available storage for the machine.

Banfa 597 Posting Pro Featured Poster

Does the program crash if you select option 5 without selecting any other option?

The code you have posted does not contain any obvious errors which means the error is else where. This is not entirely unusual, if some sort of undefined behaviour has been invoked it would be quite normal for the crash to happen in a place in the code completely apart from the location of the error.

A ha, I've spotted the error.

You are passing BankAccounts into menuSelection by value. Assuming that your BankAccounts::~BankAccounts dealloctates all the data and given that BankAccounts does not have a copy constructor and given the recursive way you call menuSelection rather than using a loop an iterating that means that the first time you call menuSelection it copies h. You select a menu option, it performs the function and calls menuSelection again copying h again. When you exit it deletes h deleting the data that it uses but because you have no copy constuctor for BackAccounts that is the same data that all the copies use to. When you exit (option 5) menuSelection and the local copy of h is deleted trying to deleting the internal data which has already been deleted causing the crash.

That it randomly works for option 4 is a random artifact of the undefined behaviour of deleting the same memory twice.

You need to do the following

  1. Pass BackAccounts to menuSelection by reference
  2. Do not call menuSelection recursively, ultimately you will always run out of …
Banfa 597 Posting Pro Featured Poster

In C arrays can't be passed as arguments (or return values directly either) you can only pass pointers. Additionally C does not have 2 (or multi) dimension arrays when you declare int a[10][10] you are not declaring a 2 dimensional array but rather an array of arrays (a subtle but important distinction).

For any array using its name without an index provides a pointer to the first element in the array so for an array of arrays using the name provides a pointer to an array, the type of a is int (*)[10] and that is what you want to pass to your function which means that the prototype needs to be void input(int a[][10], int b, int c) or void input(int (*a)[10], int b, int c); and when you call it you can just pass the name of your array of arrays input(a, m, n);

Banfa 597 Posting Pro Featured Poster

Don't declare lots of individual vectors in Company declare a container of vectors, for example

a vector of vectors:
vector<vector<Employee*> > Location; // Each location has a position

a map of vectors:
map<int, vector<Employee*> > Location; // Each location has an id number

alternative map of vectors:
map<string, vector<Employee*> > Location; // Each location has an name

Then just iterator through or find in the container (map or vector) and call the Employee vector.

void Company::OrganizeLocation(const string& location){
  map<string, vector<Employee*> >::value_type office;

  office = Location.find(location);

  for(unsigned int i=0; i<office.second.size(); i++) {
    office.second[i]->AccessorFunction1();
    office.second[i]->AccessorFunction2();
    office.second[i]->AccessorFunction3();
  }
}

Or something like that.

Banfa 597 Posting Pro Featured Poster

Your problem is in your array class, you have declared half you data members at the top of the class (line 9) and then some more half way down (line 42) and as a result you have 2 size members which you use interchangeably but you only initialize one of them.

1. Put all of the class data members in the same place
2. Remove 1 of the 2 size members

Banfa 597 Posting Pro Featured Poster

dptr and bptr_1 both point to the same allocated objected. You should only delete an object once, as soon as you delete it the pointer becaomes invalid and any access to that pointer, either dereferencing it or trying to delete it again is undefined behavior.

You allocate the object pointed to by dptr and bptr_1 at line 22 but then you try to delete it at lines 32, 46 and 52. This will always cause an error.

Only delete an object once.

Banfa 597 Posting Pro Featured Poster

Your post links are not working for me and a quick scan of the code shows no obvious problem (not to me again at least)

Banfa 597 Posting Pro Featured Poster

That just ain't how you do it, you need to implement (overload) ArrayOfTypes::operator[] and MyType::operator= separately to achieve what you want not try and do it together which is presumably this

ArrayOfTypes array;
MyType value;

array[10] = value;

ArrayOfTypes::operator[] returns a reference to a location in the array which can then be used to invoke MyType::operator= to assign to that location

class ArrayOfTypes
{
public: // ?
  vector<MyType> P;
     
  MyType& operator [](int I)
  {
    // Validate I in range ?
    return P[I];
  }

  // Implement a const version too for calling in const contexts to read the array
  const MyType& operator [](int I) const
  {
    // Validate I in range ?
    return P[I];
  }
};
class MyType
{
public:
  const MyType& operator=(const MyType& cpy)
  {
    // Don't copy self
    if (this != &cpy)
    {
      // Code to copy a MyType
    }

    return *this;
  }
};
triumphost commented: THANLS!! I solved it! +6
Banfa 597 Posting Pro Featured Poster

I can't use a dense matrix. I'm trying to store a dense matrix filled with numerous 0 values as an array of structs, which only holds significant values (ones not equal to 0). I am then trying to display that array of structs in the same format as the original dense matrix, so main is unaware that the matrix is beeing stored differently from a full 2D array.

I'm aware of that, I not suggesting you use a dense matrix, I'm suggesting you use a sparse matrix internally to your own class implemented using a std::map to handle all the look-up and data storage and allocation needs leaving you to concentrate on implementing the logic of the sparse matrix and removing from you the need to implement memory allocation, look-up functions and other utilities.

Banfa 597 Posting Pro Featured Poster

A-ha well the answer is yes there is, pre-pend a ::

::shutdown(socketId);

this will call the method defined at the global scope (i.e. the one in the C WinSock2 API).

Ketsuekiame commented: Solution as requested, with example. Clear and concise. :) +9
Banfa 597 Posting Pro Featured Poster

You need to explain more fully. It sounds like this is really a C question, you appear to be calling a C API even if your program is written in C++.

Are you saying that you are trying to write you own method called shutdown but you still want to be able to call the shutdown method in the API? If so then just use a different name for your method.

Banfa 597 Posting Pro Featured Poster

You could implement this fairly easily with a std::map rather than writing all your own code.

However clearly in your valueAt method you need to be iterating over the entire array not just performing a single if test. Your MatrixType must surely store a std::vector (or array) of oneitem and the length of that array (vectors provide their length). You need to iterate over the whole array testing each location until you find one that matches or return 0.0 if none match.

With a std::map you could have a key class

class MatrixKey
{
public:
  MatrixKey(int r, int c) : row(r), col(c)
  {
  }

  // Implement various getters, setters and comparison operators

private:
   int row, col;
};

Then declare your map std::map<MatrixKey, float> , use it internally to MatrixType when you need to find a value create a MatrixKey for row/col look it up in the map and if it isn't found return 0.0;

Banfa 597 Posting Pro Featured Poster

The real answer is that the overhead of calling a virtual function is so low that it is unlikely to cause you a problem in the majority of cases. This is definitely a case of trying to solve a problem before you know it exists.

In all likely hood your implementation with virtual functions will work plenty fast enough, you should build your solution correctly, with virtual functions, and then only start looking for ways of speeding it up if it turns out that it doesn't meet its performance criteria (go fast enough).

The problem with your proposed solution is that you can't call the functions through the base class, or more likely a base class pointer or reference. If you try you will call the functions in the base class rather than the functions in the derived class. i.i. std::vector<BasicShape&> will not have the behaviour you expect or probably want.

On the other hand if you don't need to call the functions through the base class then why do you need a base class at all, get rid of it and then at least there wont be an issue in the code waiting to rear its head when someone who doesn't know the functions aren't virtual treats them like they are.

Banfa 597 Posting Pro Featured Poster

You can use Visual Studio its OK. But if you are using Linux and Windows you may want to try something like Code:Blocks or Eclipse which are multi-platform and run on both Linux and Windows, that way you only have to learn the ins and outs of 1 IDE that you can use everywhere.

Both those IDEs use gcc on Linux and MinGW(a gcc port) on Windows.

Banfa 597 Posting Pro Featured Poster

It would help if you posted the entire error message because following the text "unresolved external" is usually the name of the symbol it is unable to find.

Banfa 597 Posting Pro Featured Poster

You are not taking account of escaped characters in strings, for example how would your code cope with the string "\"//" .

You are not taking account of character constants, how would you software cope with '"' This while ( (ch=fgetc(fd)) != (feof(fd)) ) is wrong and might well result in your reading past the end of the file. I suggest you read up on the return value of the 2 functions called.

Banfa 597 Posting Pro Featured Poster

The error probably appears random because you are calling gai_strerror when you should be calling strerror.

Banfa 597 Posting Pro Featured Poster

At line 100 this letters[ ((i % 100)/10)* 10 ] + letters[ i%10 ] can be replaced with letters[ i % 100 ] Think about say 345, this is working out the number of letters in 45, you method adds the number of letter in 40 (forty) and 5 (five) however if you are calculating letters in 345 you have already calculated letters in 1 - 99 so you can just use the number of letter in 45(forty five).

This may also fix you problem because now consider 317, you code calculates number of letters in 10(ten) and number of letters in 7(seven) which is 8 but you actually need number of letters in 17(seventeen) or 9.

Banfa 597 Posting Pro Featured Poster

You shouldn't be putting paths into #include statements on the whole, it makes it very hard to take the code to another computer unless it has exactly the same hard-drive and directory set-up.

You can pass the directory(ies) to search for include files into the compile normally using the -I switch or set it in your IDE in the project properties.

Banfa 597 Posting Pro Featured Poster

But that doesn't mean I didn't compile. That was because I tried something else on it before I posted the code. It doesn't work still. Nothing gets copied.

I hope I don't really need to say this but it really is best to post the correct code version when you are asking a question.

It seems there's some problem in the while loop. It seems not to copy anything. I cannot figure out why. Please help.

You mean the program produces no output? Or rather

string1: Hello
Copying string1 to string2....
Now string2:

Be precise when describing your problems, the program output and the expected program output it will help us to help you.

Your length function is wrong, as has been highlighted already.

Also you code does not allocate space for the NUL ('\0') terminator that C uses at the end of its strings and you don't put a NUL terminator into the copied string.

Banfa 597 Posting Pro Featured Poster

Of course like this

#define ROOT "C:\\SomeRoot\\"
#define SUB_DIR ROOT "SubDir\\"

A rarely use feature of C++ (and C) is the the compiler automatically contatinates contiguous strings.

A better question is should you given this is C++ or should you just use constant objects

const std::string root = "C:\\SomeRoot\\";
const std::string subdir = root + "SubDir\\";
Banfa 597 Posting Pro Featured Poster

Have you compiled the latest code you have posted?

Banfa 597 Posting Pro Featured Poster

char* temp = (char*) malloc(sizeof(*string1)); Consider string1, what type is it? char * from the function prototype.
In that case what type is *string1? If string1 is char * then dereferencing it gives char.
What does sizeof(char) return? 1 (by definition in the C standard)

I do not believe you wanted to allocate an array of 1 byte, I assume you want to allocate enough memory to hold the string what string1 points to. You need to count the number of characters that string1 points to (and then add 1 for the terminator), equivalent to strlen(string1) + 1 but presumably you are not allowed to use strlen either so you may have to write your own version of this.

Your loop looks OK to me but then consider string2 = &temp; What does this do? Alters the value of string2 which is a local variable. Since the variable is local that change is lost when the function exits so the function alters nothing outside itself. You want to return the string that temp now points to, that means that you need to alter something outside the function and that normally means dereferencing a pointer passed into the function to alter what it points to (assuming you are not returning the value). You need something that looks like *string2 = ???; , I leave the ??? for you to fill in.

Finally consider how you call your function copyString(string1,string2); From above we now that string2 …

Banfa 597 Posting Pro Featured Poster

It has no formal definition so its meaning is defined by the context.

Normally it just means group of related things so a module could be a group of related classes or a group of related source files, possible with-in a single process or in separate processes.

I think in your quote it problem just means "a chunk of code".

gozlemci commented: for your interest +0