function/macro sizeof(p1)
sizeof is not a function or a macro it is an operator.
function/macro sizeof(p1)
sizeof is not a function or a macro it is an operator.
Also it's not really overloading, if you put both into a single program you would get an error, it has to be one or the other. True overloading, like C++ would allow both function definitions to co-exist, if this where not main. C++ also does not allow overloading of main like this in the same program almost certainly because it only makes sense to have a single entry point.
Sorry about that I missed that the thread was in the C not the C++ forum.
Be careful with strtok
, it is very non-reentrant and I would avoid it altogether if you are writing a multi-threaded application. You can always do what strtok does with some fairly simple pointer manipulation.
You can read the file line by line with fgets
.
You have defined the TPhysics constructor at both line 32 and 52
You have a couple of options.
This sounds like it is a porblem caused by putting locks inside a loop without putting in anything that holds them up.
The thread reading from the socket should be held up by the socket comms, that is while it is not receiving any data it should not be trying to access the multimap.
Your main thread strictly has nothing to hold it up except that it only needs to process if there is something there to process. You need to use an extra object, a semaphore say. A semaphore is a sychronisation object that can be waited on that keeps a count, so every time the socket queue puts an entry in the multimap it posts to the semaphore and the main thread waits on the semaphore to be posted and then reads from the multimap.
The compiler error message either before of after that should give the line of you code that has produced this error. When posting compiler output post the complete output with the relevent lines of your source code.
I feel that someone should point out that having public member variables is generally very poor practice. The coding standards at my work require all member variables to be private.
In the first program you wanted each recursion to output a result where as in the second recursion you just wanted the result of the whole recursion.
You have no output (cout) calls in your recursion in either case; this does not matter for the second program as you only want the overall result so it works. However in the first program you wanted an output at each stage of the recursion which doesn't happen because you didn't put in an output statement.
A simple page request from a browser looks something like
GET /example.html HTTP/1.1
Host: www.example.com
(actually with an extra newline at the end of it but the code parser on this site wont show it.)
At line 68 - 74 of your code you make no attempt to parse this request but just treat the received data as though the browser has sent you a file name. Since the browser did not just send you a file name unsurprisingly you code fails to open the file.
Line 11: Undefined behaviour: you call strlen on an unititialised string, this could easily lead to memory accesses outside the boundaries of the array string. May be you meant to do this after string is requested from the user.
Line 13: Format string error: %c tells scanf to get a character from stdin not a string, perhaps you meant %s or you could have used fgets to prevent buffer overflow.
Line 15: Format string error: %c tells scanf to get a character from stdin not a string, perhaps you meant %s or you could have used fgets to prevent buffer overflow.
Line 16: Undefined behaviour: random is an array with size 20, that means valid index values are 0 <= index < 20. Using and index of 20 accesses memory outside the boundaries of the object.
Line 16: Language Error: srand returns void, i.e. nothing, you can not assign it to anything.
Line 17: Logic Error: i has the range 0 <= i <= j. Even assuming j had been correctly calculated at line 11 this should be range should be 0 <= i < j, if the string is length 3 then valid indexes for characters in it are in the range 0 - 2.
Line 19: Logic Error: xoring with random[i] with i in the range 0 <= i <= j but at no time are any of the entries in random initialised to anything.
Line 20: Language Error: Attempt to assign an array of char to a …
Of course the way the function min is written it is very likely not to work, cause a segfault even because it accesses the 1000th element of an array of size 6.
Does database.txt use '\n' as end of line characters?
Does database.txt have a '\n' on the last line in the file?
That is because you still have 3 loops, get rid of the third loop as I showed you. The problem with your implementation is that because of the nested loops it has a complexity of N^3. By removing a loop you reduce the complexity to N^2 which makes a huge difference to execution time.
It is slow because of the number of nested loops you use.
If I just compile the C++ code I get the following runtimes
Compiler Execution
Code Optomised Time
Your Original Code No 7.237s
Your Original Code Yes 1.144s
Rewritten With 2 Loops No 0.018s
Rewritten With 2 Loops Yes 0.002s
You ought to be able to get at least as good as the unoptomised compilation of the C++ code.
Also the code in assembly at lines 9-10 does not implement either the equation of you C++ code or the equation in the comments.
What you should do is
1 Not free the data at line 31, you can not know that the thread has not finished with it. Test by adding a short sleep in print_thread_id
Then either
2 Use pthread_join to detect when the thread has finished running then free the memory.
or (and my personal choice)
3 Assign ownership of that memory to the thread and free the memory in the thread function itself when the thread has finished with the data
This is strickingly similar to the last posts of this thread yet somehow a different username. Check there for an answer.
Firstly I still recon you have 1 loop too many in that code. Again after the second loop you can calulate c and then check it is in the correct range. A bit of maths and an if statement is always generally going to be quicker than a loop.
To answer your question many C++ compilers can actually output the assembler for the code the are compiling, for example by using the -S switch with gcc the compiler outputs assembler to <filename>.s
Alternatively consider that your assembly routine takes 33s, my original C++ port of your assembly routine without optomisation also takes 33s but with optomisation takes 20s and accept that the C++ compiler and optomiser does a better job than you of producing assembly/machine code and just use the C++ implementation with optomisation switched on.
You have used more loops than is necassary. The thing is once you have chosen a value of a and b you can calculate the value of c that solves the equation 2a + b - c = y. You do not need a loop that checks every value of c.
In fact since you just want a count of solutions you don't even need to calculate the value of c all you need to check is that the value would be in the right range 0 <= c <= y.
Written in c++ it looks something like
for(a=0; a<=y; a++)
{
for(b=0; b<=y; b++)
{
if ((((2 * a) + b - y) <= y) && (((2 * a) + b) >= y))
{
++count;
}
}
}
This takes about 0.019s to run or if you switch on the optomiser 0.006s for an input of 2000. (NOTE with 3 loops the C++ solution was taking around 33s to complete or 20s under optomisation).
Interestingly the calculate c and then check it's in the right range solution
for(a=0; a<=y; a++)
{
for(b=0; b<=y; b++)
{
c = (2 * a) + b - y;
if (0 <=c && c <=y)
{
++count;
}
}
}
takes 0.039s with no optomisation (slower) about 0.004s with optomisation (faster) which kind of suggests the optomiser finds it easier to optomise simpler code (which makes sense).
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.
That is because in main you pass an initial value for count to check_birthdays but you do not initialise the value you pass. This is actually undefined behaviour.
A quick fix is to initialise the variable count in main (to 0) or to call check_birthdays as check_birthdays (birthdays, people);
thereby using the default parameter value of 0. However since there seems to be no need to pass an initial count value to check_birthdays a better fix might be to remove the count parameter from the function birthdays and instead use a variable local to the function.
size_t is not terribly complicated, I think you are probably reading more into it than there is.
size_t is defined in the standard as "the unsigned integer type of the result of the sizeof operator"
And that is basically it, it is an unsigned integer type. It is the type of the result of the sizeof operator but is also used by many standard library functions that return a size, strlen for example.
You should use size_t whenever you are calling an operator or library function (or function you've written yourself) that returns size_t. This enables better portability in your program and makes it more type correct.
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.
getMonth and getDay both need to be const methods they are called through const references in operator==
daysInMonth doesn't return a value for all input values
daysInMonth is missing a Birthday:: from its definition
You have some comparisons between signed and unsigned integers
How about you show us the relavent code lines and the full compiler output.
result2 and fileUser are both std::string, therefore the will match if the have exactly the same characters in them, same characters same order same case.
If they don't match then they don't have exactly the same strings in them. This is your real question, why do result2 and fileUsernever contain the same string.
This is harder to tell because you haven't told us what the input is, what the file contents are or what extractWord does.
However you best debuging option may be to output result2 and fileUser when the don't match so you can see them, then you should be able to see if you are getting any spurious characters. If you do this remeber to surround each string with some sentinel character like ' so you can see if they contain strings.
I believe you have misunderstood how setw works. setw sets the minimum width of the next field; if the field length is less than the set field width then the field is padded with spaces (or the given padding character) either to the left or right of the data until it is the minimum width.
So for left << setw(10) << "Hello"
the minimum width is 10 but Hello is only 5 characters so 5 spaces are added to the field, they are added to the right hand side since you have said you want the data on the left.
However in right << setw(4) << "World\n"
you have requested a minimum width of 4 but World\n is 6 characters, this is greater than the minimum width so no spaces are added since the field is already long enough.
If start by moving the \n out of the field and used the endl manipulator since you don't want to count the newline as part of the field and set the field width to something with greater than the size of World (5) say 10 like this
cout << left << setw(10) << "Hello"<< "*" << right << setw(10) << "World" << endl;
You get
Hello * World
Which is probably what you are after.
A C string is and array of char. It is zero terminated, that is the last char in the string (but not necessarily the array) is the ASCII nul or '\0' or plain 0 (different names for the same thing).
All characters up to the zero terminator must be printable characters.
You have an array of char char secondLetter[3];
at line 6 and 7 you set the first 2 characters of that string, to make if a C string all you have to do is set secondLetter[2] tp '\0', secondLetter[2] = '\0';
.
strcat is for concatinating 2 C strings but you have passed it 2 char, anyway there is no need for it you already have your string in secondLetter. You can not compare C strings with ==
you will compare the pointers and they are unlikely to be the same. To compare C strings you need to call strcmp
or strncmp
from the header 'cstring'
Just read it into an integer.
std::string operation;
int operand;
cin >> operation >> operand;
// verify cin is good (i.e. no input errors occured
//lookup operation and call it with operand.
// start at 3 since 1 and 2 are prime
Actually nowa days 1 is generally considered to be not prime because it is just so darn special in its own right.
Read this for a better explaination of why http://primes.utm.edu/notes/faq/one.html
Line 24 is wrong, x%x
is always 0 and x%1
is also always 0 so it is the equivilent of
if (0 == 0 && 0 == x)
Calculating is a number is prime is not trivial (except for the first few) and I would suggest that you use a function to do the calculation and have the function return a true or false
bool isPrime(int x)
{
// Code to calculate if a number is prime
}
Since your input is limited to values in the range 0-99 I would say you have 2 choices in the isPrime function; implement an algorith to check if the number is prime or just have an array of all the prime numbers in the range 0 - 99 and check to see if the number is in the array.
<pedantic>
Not time of day, number of seconds since the epoch passed so you get a different seed every time (as long as you don't manage to seed your PRNG twice with-in 1 second).
</pedantic>
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.
At line 34 you should be returning a value, -1?
What does readWaiterRecord do?
You can't talk about 'the best' compiler, you would have to give some context, for example MSVC++ is probably the 'best' compiler if you want to create MFC programs (not that I think anyone should want to do that), on the other hand for a long time if you were interested in the most efficient fastest code on an Intel based platform then the compiler produced by Intel was the 'best' (because unsurprisingly they know their own processors better than anyone else).
DEV C++ is not a compiler it is an IDE which I think used an old version of the MinGW32 compiler. Code:Blocks is similar, an IDE not a compiler that make use of a compiler supplied from someone else (again MinGW32 by default I believe but a newer version).
Visual C++ F5 (Run in debug mode) Ctrl-F5 (run)
MinGW32 a Windows g++ port does support the Windows headers but of course if you use those then you executable will be limited to running on Windows.
Post your/some of your code
At line 5 you have char* comandi[n];
but at this point n is not initialised so even if you are using C99 (as opposed to C89/C90 which doesn't allow variable length arrays) this line of code can not go well.
Change the n
for a 10
and everything works.
You do not return anything from main.
Since argc carries the number of arguments you arguably do not need to give the number of files on the command line as a separate argument (assuming that is what the 3 is)
In your loop you loop from 0 to k-1 (<k
). for the command line '3 file1 file2 file3' that means copying 3, file1 and file2 but I get the impression you meant to copy file1, file2, file3.
Not really sure what you are on about, apart what the letters stand for I know little of FFTs having forgotten all about them as soon as the need to know them disipated (about 5 pico-seconds after I left university).
A wav file does not have a frequency as such. It has a sample rate, is that what you mean? The sample rate should be in the file header. If you mean frequency(s) of the sound contain in the file then I have to say that audio analysis is something I have never done and I wouldn't really know where to start.
It entirely depends on the format of the file you wish to read.
For example a WAV file is store as a series of samples, no special library is required to read it just read the binary data.
On the other hand an mp3 file is encoded using the MPEG 2 standard. That is propriatory and even if there is a library to allow you to decode it you would like need to purchase a license to use it.
But then again if it is an ogg or flac file those are open source formats and you should be easily able to get a liobrary that you enable you to load the file.
Actually while what sepp2k says is generally true for many many platforms it is not absolutely true it rather depends on the platform's hardware and how it does addressing.
For example I worked with a microprocessor that used 16bit word addressing, that is each 16 bit address gave the location of a 16 bit word. To address a byte in assembly or machine code you needed to indicate if you wanted the high byte or low byte of the word. Because of this in C integer pointers (int) were 16 bits (integers were also 16 bits long), 2 bytes, but char and void* which had to be able to address every 8 bit byte where 17 bits and thus normally 4 bytes long.
I would say that it is possible that in such a situation it may have been better for the platform to define it bytes as being 16 bits long and stuck to straight 16 bit addressing, although I have not thought through all the ramifications of that particularly outlandish suggestion so I could easily be wrong.
There is absolutely no standard requirement for pointers to different types to be the same size.
In display you use i and an index to access pointer, however you also increment pointer so the second time round the loop you actually access the third item in the array no the second (because you moved along 1 twice).
Additionally at line 20 emp[i].name is already a pointer to the array you do not need the &.
Line 14 you declare ptr as a record *
, line 27 the function display takes as a parameter record *[]
which is equivilent to record **
. I am surprised that you did not get a compiler warning or error.
Correct the type that the function display takes as a parameter and then inside display use .
instead of ->
because ptr[i]
now evaluates to an object not a pointer to an object.
[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.
You have tried to declare all your functions inside main. You can not declare functions inside functions and while you can declare classes inside functions you probably don't want to here because then the class wont be visible to any other functions.
You code layout should have this structure
#include statements
Declaration of functions (SelectionSort, insertion_sort, total)
Definition of classes (Invoice in this case)
int main()
{
// Your code for main here
return 0;
}
Defintion of other functions such as (SelectionSort, insertion_sort, total)
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
}
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.
int a[10][10];
is same as,
int(*a)[10];
Err, NO.
The first, a is an array of 10 arrays of 10 integers.
The second a is a pointer to an array of 10 integers.
Assuming the first, int a[10][10];
, then the expression a
evaulates to a type int(*)[10];
.
Which is the same type as a in the second case.
So then break down the statment `((a+1)+1)'
a is a pointer to an array of 10 ints
a+1 increments a, the compiler knows the size of a so it increments it by that size to the next array of 10 ints in the array
(a+1) converts us from a pointer to an array of 10 ints to an array of 10 ints which evaluates to a type int *
*(a+1)+1 increments our int * point to the next one in the array
*((a+1)+1) converts out int * to an int
Basically giving the second integer in the second array of 10 ints, functionally equivilent to a[1][1]
.
I would say that, particularly in portable code, the C bitfield syntax is of no use. It is a syntactic sugar for accessing bits in an integer type that can easily be achieved using the bitwise operators (& | ~ << >>) the difference is that while using the bitwise operators you can easily write portable code the C bitfield syntax is not properly portable because it is very loosely defined. Different platforms do not need to put the bits in the same order and do not have to use the same padding bits.
In general I would avoid using C bitfield syntax.
OK you have a mutex to protect access to you data in the threads but you do not use it when access the data in main. This is an error whenever you access the data even for read you should always lock the mutex protecting its access.
It might be said that the read of the variable is atomic (i.e. can't be interrupted and is therefore safe without the mutex), it may be but you really can't be 100% sure what assembly code will be produced from your code particularly if you code is meant to be platform independent.
As to scheduling, the shecduler is not deterministict. If you need your threads to run in a specific order then you need to do it programatically. Various ways you might do this, only start thread 2 when thread 1 has finished, use some sort on sychronisation object (a semaphore for example) to hold up thread 2 until thread 1 has finished or design and write your program so that this type of synchronisation is not required.
Finally I do not thing pthread_exit does what you think it does. It exits the current thread with a return value (see http://linux.die.net/man/3/pthread_exit) it does not exit a thread identified by its id. You may want to be calling pthread_join though.
Which means if you added the switchs -Wall -pedantic
to your compiler command you code would not compile (try and see)