Banfa 597 Posting Pro Featured Poster

However if you don't know about arrays then you may want to break off trying to solve this problem and learn about arrays first since they are a fairly basic feature of the C language that you will need to know in order to do anything terribly significant.

Banfa 597 Posting Pro Featured Poster

No not anyone can access them if they are private only the class can access them. Even if you provide getters and setters still only the class can access them, that is only the class has direct access to the memory they occupy (without some serious doggy pointer manipulation). They are still safe from the outside world because the class designer has control of how they are accessed.

If they are public the class designer has no control in how they are accessed, that is down to the class user (program creator) how they access them.

You are confusing being able to get or alter the value of a data member in a controlled manor through a getter/setter with having direct uncontrolled access.

The job of encapsulation is not to stop the outside world from accessing values it needs to use the class or from setting values it needs to control the class. The purpose of encapsulation is to prevent uncontrolled access which could lead to the class being in an invalid state or containing invalid values. Getters and setters achieve this by putting some code that is under control of the class designer between the outside world and the actual member data (memory) access.

Banfa 597 Posting Pro Featured Poster

You need to start by working out what data type you will use. Clearly the largest number you will have to deal with is [TEX]$F_{100}$[/TEX] which is 354224848179261915075, a fact you can verify with a simple web search.

What data types do you have available that might hold that number? Note that you will be wanting to use integer data types otherwise you will loose precision and not get the real numbers.

Banfa 597 Posting Pro Featured Poster

Through getter setter methods we can indirectly access private data members of the class as shown in the below code. Then what is the significance of encapsulation in OOPS concept. I am not getting the appropiate answer for that. Can anyone help me?

Actually with getters and setters you are not directly accessing them, you are gaining access to their value and a method to alter them through class methods.

This is a subtle but highly significant difference, the actual code that accesses the class memory locations is reduced to a single place (externally to the class at least), the setter/getter. That means that if there is extra operations to do on getting/setting that too can be done in this single place.

Starting from your class supposed that you are in a multi-threaded environment and a decision is made that that class needs to be made thread safe. You simple and some sort of mutex object to the class and acquire it in the getter and setter before getting/setting. Now all the access to the class member is thread safe.

Now suppose that you did not have getters/setters you have public member data accessed directly in code but you have to implement the same change. You will have to find every single instance of access to the class data and add mutex protection calls to it (or implement getters and setters). This is much harder and much more prone to introduction of errors than altering 2 methods.

Banfa 597 Posting Pro Featured Poster

You ought to be able to write a QT application that wraps your classes without needing to change them...

assuming that you dsign in the first place separated user interface from implementation for example class don't cout data, the return strings which the user interface then couts.

Banfa 597 Posting Pro Featured Poster

What you also need to be aware of is that right shift of a signed value in C is a platform defined operation and may be either arithmetic shift or logical shift.

That means the the operation

-2 >> 1

is not truely portable because the result could be either -1 or 127 depending on how the compiler has implemented right shift of a signed value.

In binary(decimal equivalent)

// arithmetic Shift
11111110(-2) >> 1 = 11111111(-1)
// logical shift
11111110(-2) >> 1 = 01111111(254)

Left shift of a signed value by more than the number of the bits in the value is undefined behaviour.

Generally it is considered best practice to avoid shifting signed values.

Banfa 597 Posting Pro Featured Poster

Erm, 1020304 and 01020304 are the same number the second one just has a leading 0.

Banfa 597 Posting Pro Featured Poster

I think you will find this easier to do if you start-up a worker thread to perform your "process" leaving the original thread running the user interface.

My C++/CLR is quite rusty but I think you could use a delegate to call back to the interface thread with process updates to display and you could easily use an interprocess communications object such as an event to communicate a stop event to the background worker thread.

See System.Threading in the .NET documentation

Ancient Dragon commented: Agree +28
Banfa 597 Posting Pro Featured Poster

It is unlikely you would want a container that you hold a generic absolutely anything. On the other hand you might want a container that held several different sub-types of a type (for instance several different types of vehicle).

And that is what class hierarchies, inheritance and polymorphism are for (well one of the things). You declare a hierarchy with your base class holding the interface and any common information and in your container you hold hold pointers to base base. Because there are base class pointers you can actually store (a pointer to) any object within the inheritance tree.

Banfa 597 Posting Pro Featured Poster

No it's there because they try to call them. Generally when grepping if you have the source it is better to grep the source code no the binary library. If you did you would find that the source code attempts to call these functions but they are not defined anywhere.

And that is what "undefined reference to" means, a symbol (class name, function name, variable name) was used by a piece of source code which compiled fine because the symbol was declared, however the symbol was not defined so the linker can not resolve the reference to it.

A quick Google (or your alternative other search engine) on dcoomm will show that it is part of the Sun Performance Library which appears to be a library that Sun distributed with there compiler toolset.

I couldn't actually find a source for the library but on the other hand I did stop looking once I found out what it was.

Banfa 597 Posting Pro Featured Poster

Unfortunately, some brief searching has left me uneasy about whether C++ really guarantees that all pointers to objects (i.e. SomeClass) and primitives (i.e. long int, char, etc.) will be the same size.

I would have thought (I don't have my standard to hand to check) that C++ makes the same guarantees as C in this respect. That is it doesn't guarantee anything except that if you cast a pointer to type T to void * and cast it back to T* it will still be valid.

It certainly does not guarantee they will be the same, and in fact I have worked on platforms where they have not been the same size and even if they are the same size it doesn't guarantee that the bits in the pointers mean the same thing.

This means that code such as this

long l = 5;

// C
char *pc = (char*)&l;

// C++
char *pc = reinterpret_cast<char*>(&l);

Rely on platform defined behaviour and are strictly speaking non-portable.

I assume C++ also makes a few guarantees about casting up and down a class hierarchy.

Banfa 597 Posting Pro Featured Poster

I hope that this new_orb->mana = malloc(sizeof(int)); is a typo because its wrong and its not what is in your original listing.

If all names are fixed to 21 then you should #define a symbol to that value (21) and use the symbol throughout your code. Then if for instance the value needs to change you have only to change a single location rather than change every place in the code. A issue that gets more serious the more code and code files you have.

Finally using scanf("%s", &tlname); where the size of tlname is limited is bad practice because it is easy for the user to input more than 20 characters and cause a buffer overflow. Instead either use something like fgets or use something like this scanf("%20s", &tlname); which limits the amount of data put into the target.

Banfa 597 Posting Pro Featured Poster

1 malloc does take care of the whole struct, however those pointers point to something that is not part of the struct they are separate things.

Anyway another call to malloc for each pointer should do the trick. Remember if using strlen to get the sizes of the strings to copy you need to add 1 for the null terminator.

If this is implemented on a POSIX compliant platform and you aren't too fussed about portability you could use strdup.

Which ever method you use remember that those strings will need to be explicitly deallocated again before freeing the structure when releasing the node memory.

Banfa 597 Posting Pro Featured Poster

In Eclipse, surely you can set libraries to link to without needing this syntax.

Well yes but it does rather depend on how you have your projects set up in the first place.

Personally I think Eclipse is a bit heavy weight and confusing for a new user and I particularly dislike the way it seems to think it is a separate file system independent of the actual file system.


You might want to try something a little lighter and easier like CodeBlocks

Banfa 597 Posting Pro Featured Poster

Line 43 and 44, you copy to the char pointers fname and lname but you have not allocated any data for those pointers to point to. They are uninitialised.

Banfa 597 Posting Pro Featured Poster

Thank you so much for downloading Sparselib and having a look. I did not understand what you meant by .

You have not lost much by not understanding because I was wrong :D

I hadn't noticed that they were using .cc files and my IDE grep was set to only search .h and .cpp

Anyway what davidora is saying (and I think thay are on the right track) is that when you call the build using the makefile SparseLib++\1.7\makefile the result should be that these 3 libraries

libmv.a
libsparse.a
libspblas.a

are created in SparseLib++\1.7\lib

If when you link your application you leave these libraries out (off the linker command line) then you will get unresolved externals similar to what you have got.

The header is NOT the library, the header is just the interface to the library that you compile against. To use the library you also have to link against the binary lib file.

Banfa 597 Posting Pro Featured Poster

Sorry I was getting a little confused.

So you have the undefined reference errors?

I downloaded SparseLib and examined a couple of them

coord_double.h:66: undefined reference to `MV_Vector_int::~MV_Vector_int()'
coord_double.h:66: undefined reference to `MV_Vector_double::~MV_Vector_double()'

Those functions, the destructors on those classes, do not exist. They are defined in the right place but while all the other methods of those classes are also declared in the headers those ones aren't.

I think you are probably going to have to go through and edit the files to implement the missing functions to get this to link.

Either that or find a place that provides specific help on this library.

Banfa 597 Posting Pro Featured Poster

If those headers contain a definition or use of the symbol COMPLEX by placing it before you include the headers you change the headers and by placing it after them you don't.

BTW compiler/linker errors without the lines of code the correspond to are nearly (not quite but nearly) useless.

In the last listing it looks like you are missing a library or object file when you are linking.

Banfa 597 Posting Pro Featured Poster

The compiler probably doesn't crash after entering c because the compiler never requests that you enter c. Presumably you are actually running the program to get to the enter c phase. The program doesn't crash either, it does what you have asked and exits normally (or it does for me but then since this program exhibits undefined behaviour it is impossible to say what is happening for you).

You have the following problems

Line 4: Returning void is an extension that not all compilers support, get in the habit of returning int now.

Line 11: Unnecessarily declare c which is never initialised to anything.

Line 12: Attempt to add a and b and store the result in s before you have obtain values for a and b. Reading uninitialised/unassigned automatic variables is undefined behaviour.

Line 15: you don't scan the input return you typed so it is left in the input buffer, we'll come back to this ...

Line 19: Here where you ask for a character, the system looks at the input buffer which contains a line feed and returns that to you, no extra input is required.

Line 20: Access to the initialised variable c is undefined behaviour also this is not how you check if variable d is equal to the character c. You need to use a character constant (you can Google that).

Aia commented: Good effort. +9
Banfa 597 Posting Pro Featured Poster

As always with programs when you have a problem with your command line arguments put them in quotes -D"COMPLEX=std::complex<double>" I imagine that the command line interpreter is < as the input piping operator.

Banfa 597 Posting Pro Featured Poster

Erm, that is already a 2d array, it is not clear what your problem is.

Banfa 597 Posting Pro Featured Poster

As an array or vector of bytes

Banfa 597 Posting Pro Featured Poster

Where and how do you define your original array?

Banfa 597 Posting Pro Featured Poster

You need to stop treating it as a string!

It is not a string it is binary data and since '\0' is seen as a terminator in strings but is just another value that commonly occurs in binary data you will continue having trouble until you do.

Banfa 597 Posting Pro Featured Poster

Line 9
info.qt1 is an array, you can't perform assignment or most mathematical operations on an array. The expression info.qt1 returns a pointer to the first element of the array and the code tries to add that to info[j].sal_amount which is a float and so this is an illegal operation.


The following mathematical operations on a pointer are possible.
Addition of an integer
Subtraction of an integer
Difference (subtract of) between 2 pointers


P.S. Line 4 creates indexes from 1 to 3 inclusive. However in C arrays are indexed from 0 (however that may be intentional).

Banfa 597 Posting Pro Featured Poster

Of course strlen() returns the number of chars - NULL but in a string indexing starts from 0.
So
str[11] is sufficient to hold 11 characters plus 1 null char. As 0-11 is 12 characters in all

No very VERY wrong. strlen does not return the size of the array holding the string it returns the number of characters in the string up to but not including the NULL.

Try this code for proof

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
   char Text[] = "Hello World"; // Allocate an array just the right size of the text

   //Now print the two strings
   printf("Text: %s\n", Text);
   printf("strlen: %d\n", strlen(Text));
   printf("size: %d\n", sizeof Text);
}

And you will see that strlen returns a value 1 less than the size of the array required to hold the string.

Output

Text: Hello World
strlen: 11
size: 12

Banfa 597 Posting Pro Featured Poster

You might try having a look on http://www.zilog.com/

and not the the header file is unlikely to be any use without the accompanying binary library.

Banfa 597 Posting Pro Featured Poster

i have red in my lectures, that the following code

m-=m*3-h++*2;

can also be written as

m=m-m*3-h++*2;

No m-=m*3-h++*2; can be written as m=m-(m*3-h++*2); Those parentheses make all the difference because when you factor them out it becomes m=m-m*3+h++*2; Which is different to m=m-m*3-h++*2;

farhanafzal commented: Thanx +1
Banfa 597 Posting Pro Featured Poster

That is not a very easy macro definition to demonstrate the other error but consider this code using that macro ~SQR(2) . What do expect the output to be, what is it?

This is normally more easily demonstrated with the macro in question uses + rather than *.

Banfa 597 Posting Pro Featured Poster

p does not point to any ClsA objects, p points to a pointer to ClsA objects.

A pointer is a built in type and has no constructor or destructor. So no destructor call is required for that delete statement.

Presumably in the code lines 21-22 you have something that does p[0] = new ClsA[10]; and the destructor will be called when you delete this memory delete[] p[0];

Banfa 597 Posting Pro Featured Poster

I'm still looking for the right way to implement reserve::add() with my current code I get a Seg Fault

void MultiEns::Elem::reserve::add(void *p){
	Elem *tmp = teteReserve->suiv;
	teteReserve->suiv = (Elem *) malloc(sizeof (p));
	teteReserve->suiv->suiv = tmp;
}

This is C++ generally don't use malloc use new.

Line 3 malloc(sizeof (p));

What is p? A void pointer.
How big is p? Depends on your system but probably 32bit system 4 bytes 64 bit system 8 bytes.
You cast the return to Elem *, how big is Elem? Probably 8 with next in the last 4 bytes.

On a 32 bit system you allocate 4 bytes on line 3 and on line 4 write to the 4 bytes following it.

New would solve the problem because it is type safe, that is a very important feature of C++ over C which is why it is best to do things the C++ way. teteReserve->suiv = new Elem; Also the whole use of teteReserve->suiv in this function suggests that you actual head pointer is teteReserve->suiv, that is you have allocated a Elem node to hold the head pointer in suiv . Except that I do not see anywhere where you do actually allocate an Elem and assign it to teteReserve.

Personally I don't like this Using a node as the head pointer technique though I see a lot of people doing it to me it confuses the meaning of the head pointer.

Banfa 597 Posting Pro Featured Poster

No your question is so lacking in detail that it is not answerable.

Banfa 597 Posting Pro Featured Poster

Looking at the slide code you found I have these comments

class reserve {
        public:
            static void constructReserve(int);
            static void destructReserve();
            static bool empty();
            static Elem* get();
            static void add(void *);
            static void printReserve();
            static Elem* headReserve;
        };
  • It's all static (as someone else mentioned) while you could do it that way it doesn't lend itself to reuse. If you really only want on of them then use the single design pattern (which you can Google).

  • empty and printReserve are utilities and not part of the main function of the class.
  • get is the equivalent of new but doesn't do a full job, when you call new you can provide the parameter with which to construct the object. Get provides no way to do this. If returning an object what has been constructed using the default constructor is fine then get can work but given that you might be re-using blocks get wil then have to make sure it initialises every block it returns.
  • add is the equivalent of delete but takes the wrong pointer type. Most of the time void * should be unnecessary in C++.
  • headReserve is public, this is a disaster, letting code outside the class have access to the internal management data removes most of the point of having a class to do this which is encapsulation of the functionality.

I would use a class with a public interface something like this (with no utility frills added)

class reserve {
public: …
Banfa 597 Posting Pro Featured Poster

|That is because *n is a char and 275 is larger than a char. You need to cast to a pointer to int so that you are storing an actual integer.

However I would strongly discourage this whole code structure, directly accessing the byte of members of a structure through a char pointer, in any commercial project.

Banfa 597 Posting Pro Featured Poster

Is there any alternative to polling to do what?

For example in communications there is often an alternative to get the system to tell you when there is data waiting rather than polling for it.

Banfa 597 Posting Pro Featured Poster

Have you heard of the placement new syntax? Placement new constructs a new object without allocating memory for it. You have to provide the buffer yourself.

char *buf = <allocate data in you onw method>;

Elem* normal = new Elem(0 NULL); // Normal new call allocates data from heap
Elem* placement = new (buf) Elem(0 NULL); // Placement new call uses data pointed to by buf to construct Elem in

However I would use a separate class to handle the memory allocation (you could make it a template if you need to handle many different types).

The public interface would include allocate and free methods.

The advantage of this is that you encapsulate your allocation code from your functional code. The initial implementation of your allocator can use new and delete for simplicity and to get everything working. You can then replace that with whatever algorithm you want at a later time, including having a pre-allocated list of available entries and allocating more when you run out.

Banfa 597 Posting Pro Featured Poster

Hard to tell without seeing the actual output and the desired output.

Banfa 597 Posting Pro Featured Poster

You do not invoke the output of your program with

./test.cc

That is you source file.

The output will be a.out so you would use

./a.out

as you command line

Banfa 597 Posting Pro Featured Poster

the problem now is how do i remove the duplicate strings from an array. I want to copy strings from array A[] to array B[] without duplicate entries. please somebody suggest a code for this.

AND

how to i detect whether the entries in an array are over without knowing the count as to how many entries exist??

Before you add a string to A[] check all the entries that are already in it to see if any are the same as the one you are about to add and don't add it if any are.

AND

You can't storing the number of used entries in an array is an integral part of being able to use it.

Banfa 597 Posting Pro Featured Poster

That does not look like a likely runtime error from the code you have posted.

Perhaps you had better post the command line you are using.

Banfa 597 Posting Pro Featured Poster

I agree but if you are going to use time you will need to use a smaller unit of time so that you get proper results.

Is that time in seconds? Then you need to find a way to measure the time in milliseconds.

Also the problem with time, if you are not careful, on a multi-core, mutli-tasking system is that you accidentally measure elapsed time rather than processing time for your algorithm. If you program gets interrupted a lot by a higher priority process then that could severely skew your results.

Banfa 597 Posting Pro Featured Poster
char Post_Request[998576];//998576
char Response[8576]; //2018

I don't believe that putting over 1 million bytes onto the stack is a good idea. generally speaking best practice is to keep the data on the stack relatively small.

The method you are using to create your request with all those sprintfs lacks something too. It isn't terribly efficient because you keep copying lots of the data over and over, for example "POST %s HTTP/1.1\r\n" gets copied 14 times for 1 request.

I would have thought that using a std::vector<char> to hold the response, and use a std::string or std::stringstream to create the headers in would be better. You can then use the std::copy algorithm or std::vector::insert to copy each header into the response a single time and the same method can be used to copy your ReadBuffer into the vector too.

vector<char> Post_Request;
ostringstream ss;
string text;

ss << "POST " << PHP_Script << " HTTP/1.1\r\n";  // Don't use endl HTTP requires specific end line characters
text = ss.str();
Post_Request.insert(Post_Request.end(), text.begin(), text.end());

...

Post_Request.insert(Post_Request.end(), ReadBuffer, &ReadBuffer[BufferSize]);

That still invlodes copying "POST" 3 times but it only copies Readbuffer once instead of 5 times.

Also it will automatically allocate data to hold everything (although you could make things more efficient by setting the vectors capacity before you use it based on BufferSize and the size of various other string parameters. And it puts that data on the heap rather than the stack which for large temporary buffers is probably …

Banfa 597 Posting Pro Featured Poster

" is a special character as it delimits the string. If you want a " in your string you need to escape it using \ so the compiler treats it as a character in the string and not a string delimiter like this "\""

Banfa 597 Posting Pro Featured Poster

That is because \ is the escape character in string literals in C (and C++) so '\t' is a tab character and '\p' is p (I think). To get an actual slash you need '\\'

Banfa 597 Posting Pro Featured Poster

OK you CAN assign a structure pointer to a char point but it is not a terribly good idea and doesn't serve any good purpose on the whole.

On your malloc line you assign a value to n, it points at some allocated data.

Then on the next line you assign to n the value of p. Firstly this is a memory leak, you have just lost the pointer to the allocated memory and no-longer have any means to free it. Secondly p is not initialised to anything and strictly speaking using an uninitialised automatic scope variable is undefined behaviour.

Then you try n->a . N is a char pointer, it has no members, *n is a char. You could use p->a but p does not have a valid value yet.

I don't know what you are trying to achieve but I suspect you want something more like

struct name* p;
p = malloc(sizeof *p);
p->a = 3;

/* More code here */

/* Now I have finished with p */
free(p);

No need for any char pointer.

Banfa 597 Posting Pro Featured Poster

Line 49 does not have the same separators as line 28

It is no good just saying it wasn't successful, we do not know what it was meant to do or what it actually did unless you tell us.

Banfa 597 Posting Pro Featured Poster

I am not very experienced in programming, but I think you can do this without using any of the functions like atoi(), etc....

You could do but why re-write code that has already been implemented for you in the library? You are just wasting time and effort that could be put into the program logic proper.

Also what you suggest takes no account of white space but most users would be put out if you rejected there input because they happened to put a space before or after the number.

Using stringstream or strtol takes a lot of the hard work out of the job, which isn't to say that some experienced programmers wouldn't go ahead and do it the way you suggest.

Banfa 597 Posting Pro Featured Poster

Well you can look for a correlation between the size of the item the calculation is dependent on (data size) and the resultant size of the calculation, which could in fact be any column. However your run time column is clearly useless as it does not have the resolution to show anything.

However using either comparisons or moves could work.

Excel, or any other spread sheet is a good tool for this. Plot the data in a graph and then get excel to calculate a trend line. In this case it appears that both comparisons and moves have a near linear relationship to data size.

However the problem with mathematical analysis of this data is the lack of data points. 4 really isn't a big set and that makes it easy for the maths to go wrong.

Banfa 597 Posting Pro Featured Poster

A fair point and I probably should have pointed out that the C standard library is available in C++.

What I was trying to combat was the tendency of people who have learnt C first to just use the C method they know rather than looking for the C++ way even if they then discard that method as inefficient or for some other valid reason.

I am mildly surprised that using a stringstream is less efficient because those C++ gurus definitely seemed to have made execution efficiency a priority in other areas. On the other hand I have also felt that the C++ stream library lacked the elegance displayed by say the STL containers. The shear amount of code required to output formatted data compared to what you can do with printf is daunting.

Banfa 597 Posting Pro Featured Poster