Вы находитесь на странице: 1из 43

How can I implement opaque (abstract) data types in C?

One good way is to use structure pointers (perhaps additionally hidden behind typedefs) which point to structure types which are not publicly defined. In other words, a client uses structure pointers (and calls functions accepting and returning structure pointers) without knowing anything about what the fields of the structure are. (As long as the details of the structure arent needed--e.g. as long as the -> and sizeof operators are not used--C is perfectly happy to handle pointers to structures of incomplete type.) Only within the source files implementing the abstract data type are complete declarations for the structures actually in scope.

Why does the simple line-copying loop while(!feof(infp)) { fgets(buf, MAXLINE, infp); fputs(buf, outfp); } copy the last line twice? In C, end-of-file is only indicated after an input routine has tried to read, and failed. Usually, you should just check the return value of the input routine: while(fgets(buf, MAXLINE, infp) != NULL) fputs(buf, outfp); In almost all cases, theres no need to use feof at all. (feof, or more likely ferror, may be useful after a stdio call has returned EOF or NULL, to distinguish between an end-of-file condition and a read error.)

How can I recover the file name given an open stream or file descriptor? This problem is insoluble. Under Unix, for instance, a scan of the entire disk (perhaps involving special permissions) would be required, and would fail if the descriptor were connected to a pipe or referred to a deleted file (and could give a misleading answer

What is the difference between these initializations? char a[] = "string literal"; char *p = "string literal"; My program crashes if I try to assign a new value to p[i]. A string literal can be used in two different ways: 1. As the initializer for an array of char, as in the declaration of char a[] , it specifies the initial values of the characters in that array (and, if necessary, its size). 2. Anywhere else, it turns into an unnamed, static array of characters, and this unnamed array may be stored in read-only memory, and which cannot be modified. In expression context, the array is converted at once to a pointer, as usual, so the second declaration initializes p to point to the unnamed arrays first element.

How do I round numbers? The simplest and most straightforward way is with code like (int)(x + 0.5)

Cs floating to integer conversion truncates (discards) the fractional part, so adding 0.5 before truncating arranges that fractions >= 0.5 will be rounded up. For negative numbers, though, for which you could use something like (int)(x < 0 ? x - 0.5 : x + 0.5), or play around with the floor and ceil functions.) You can round to a certain precision by scaling: (int)(x / precision + 0.5) * precision Handling negative numbers, or implementing even/odd rounding. Note that because truncation is otherwise the default, its usually a good idea to use an explicit rounding step when converting floating-point numbers to integers. Unless youre careful, its quite possible for a number which you thought was 8.0 to be represented internally as 7.999999 and to be truncated to 7.

How can I handle floating-point exceptions gracefully? You can define a function matherr which will be called when there are certain floating-point errors, such as errors in the math routines in <math.h>.

What is assert() and when would I use it? It is a macro, defined in <assert.h>, for testing ``assertions. An assertion essentially documents an assumption being made by the programmer, an assumption which, if violated, would indicate a serious programming error. For example, a function which was supposed to be called with a nonnull pointer could write assert(p != NULL); A failed assertion terminates the program. Assertions should not be used to catch expected errors, such as malloc or fopen failures.

What is hashing? Hashing is the process of mapping strings to integers, usually in a relatively small range. A ``hash function maps a string (or some other data structure) to a bounded number (the ``hash bucket) which can more easily be used as an index in an array, or for performing repeated comparisons. An extremely simple hash function for strings is simply to add up the values of all the characters: unsigned hash(char *str) { unsigned int h = 0; while(*str != \0) h += *str++; return h % NBUCKETS; }

A somewhat better hash function is unsigned hash(char *str) { unsigned int h = 0; while(*str != \0) h = (256 * h + *str++) % NBUCKETS; return h; } which actually treats the input string as a large binary number (8 * strlen(str) bits long, assuming characters are 8 bits) and computes that number modulo NBUCKETS.

What do ``lvalue and ``rvalue mean? An lvalue is an expression that could appear on the left-hand sign of an assignment; you can also think of it as denoting an object that has a location. An rvalue is any expression that has a value (and that can therefore appear on the right-hand sign of an assignment).

Why isnt my procedure call working? The compiler seems to skip right over it. Does the code look like this? myprocedure; C has only functions, and function calls always require parenthesized argument lists, even if empty. Use myprocedure(); Without the parentheses, the reference to the function name simply generates a pointer to the function, which is then discarded.

What is C C is a programming language

Why arent the sizes of the standard types precisely defined? Though C is considered relatively low-level as high-level languages go, it does take the position that the exact size of an object (i.e. in bits) is an implementation detail. (The only place where C lets you specify a size in bits is in bit-fields within structures.) Most programs do not need precise control over these sizes; many programs that do try to achieve this control would be better off if they didnt. Type int is supposed to represent a machines natural word size. Its the right type to use for most integer variables.

I can then define these typedefs to be int, short, long, etc. depending on what machine Im

using. That should solve everything, right? If you truly need control over exact type sizes, this is the right approach. There remain several things to be aware of: There might not be an exact match on some machines. (There are, for example, 36-bit machines.) A typedef like int16 or int32 accomplishes nothing if its intended meaning is ``at least the specified size, because types int and long are already essentially defined as being ``at least 16 bits and ``at least 32 bits, respectively. Typedefs will never do anything about byte order problems (e.g. if youre trying to interchange data or conform to externally-imposed storage layouts). You no longer have to define your own typedefs, because the Standard header <inttypes.h> contains a complete set.

What should the 64-bit type be on a machine that can support it? The new C99 Standard specifies type long long as effectively being at least 64 bits, and this type has been implemented by a number of compilers for some time. (Others have implemented extensions such as __longlong.) On the other hand, its also appropriate to implement type short int as 16, int as 32, and long int as 64 bits, and some compilers do.

Whats wrong with this declaration? char* p1, p2; I get errors when I try to use p2. Nothing is wrong with the declaration--except that it doesnt do what you probably want. The * in a pointer declaration is not part of the base type; it is part of the declartor containing the name being declared. That is, in C, the syntax and interpretation of a declaration is not really type identifier ; but rather base_type thing_that_gives_base_type ; where ``thing_that_gives_base_type--the declartor is either a simple identifier, or a notation like *p or a[10] or f() indicating that the variable being declared is a pointer to, array of, or function returning that base_type. (Of course, more complicated declarators are possible as well.) In the declaration as written in the question, no matter what the whitespace suggests, the base type is char and the first declarator is ``* p1, and since the declarator contains a *, it declares p1 as a pointer-to-char. The declarator for p2, however, contains nothing but p2, so p2 is declared as a plain char, probably not what was intended. To declare two pointers within the same declaration, use char *p1, *p2; Since the * is part of the declarator, its best to use whitespace as shown; writing char* invites mistakes and confusion.

Im trying to declare a pointer and allocate some space for it, but its not working. Whats wrong with this code? char *p; *p = malloc(10); The pointer you declared is p, not *p.

Do all declarations for the same static function or variable have to include the storage class static?

The language in the Standard does not quite require this (whats most important is that the first declaration contain static), but the rules are rather intricate, and are slightly different for functions than for data objects. (There has also been a lot of historical variation in this area.) Therefore, its safest if static appears consistently in the definition and all declarations.

What does extern mean in a function declaration? extern is significant only with data declarations. In function declarations, it can be used as a stylistic hint to indicate that the functions definition is probably in another source file, but there is no formal difference between extern int f(); and int f();

Whats the difference between using a typedef or a #define for a user-defined type? In general, typedefs are preferred, in part because they can correctly encode pointer types. For example, consider these declarations: typedef char *String_t; #define String_d char * String_t s1, s2; String_d s3, s4; s1, s2, and s3 are all declared as char *, but s4 is declared as a char, which is probably not the intention. #defines do have the advantage that #ifdef works on them. On the other hand, typedefs have the advantage that they obey scope rules (that is, they can be declared local to a function or block).

Whats the difference between these two declarations? struct x1 { ... }; typedef struct { ... } x2; The first form declares a structure tag; the second declares a typedef. The main difference is that the second declaration is of a slightly more abstract type--its users dont necessarily know that it is a structure, and the keyword struct is not used when declaring instances of it: x2 b; Structures declared with tags, on the other hand, must be defined with the struct x1 a; form. (Its also possible to play it both ways: typedef struct x3 { ... } x3; Its legal, if potentially obscure, to use the same name for both the tag and the typedef, since they live in separate namespaces.) Whats wrong with this initialization? char *p = malloc(10); My compiler is complaining about an ``invalid initializer, or something. Is the declaration of a static or non-local variable? Function calls are allowed in initializers only for automatic variables (that is, for local, non-static variables).

What is the difference between these initializations? char a[] = "string literal"; char *p = "string literal";

My program crashes if I try to assign a new value to p[i]. A string literal (the formal term for a double-quoted string in C source) can be used in two slightly different ways: 1. As the initializer for an array of char, as in the declaration of char a[] , it specifies the initial values of the characters in that array (and, if necessary, its size). 2. Anywhere else, it turns into an unnamed, static array of characters, and this unnamed array may be stored in read-only memory, and which therefore cannot necessarily be modified. In an expression context, the array is converted at once to a pointer, as usual, so the second declaration initializes p to point to the unnamed arrays first element. Some compilers have a switch controlling whether string literals are writable or not (for compiling old code), and some may have options to cause string literals to be formally treated as arrays of const char (for better error catching).

Why doesnt struct x { ... }; x thestruct; work? C is not C++. Typedef names are not automatically generated for structure tags. Either declare structure instances using the struct keyword: struct x thestruct; or declare a typedef when you declare a structure: typedef struct { ... } x; x thestruct;

Why does the declaration extern int f(struct x *p); give me an obscure warning message about ``struct x declared inside parameter list? In a quirk of Cs normal block scoping rules, a structure declared (or even mentioned) for the first time within a prototype cannot be compatible with other structures declared in the same source file. To resolve the problem, you should probably rearrange things so that the actual declaration of the structure precedes the function prototype(s) using it. (Usually, both the prototype and the structure declaration will end up in the same header file, so that the one can reference the other.) If you must mention a hitherto-unseen structure in a prototype, precede the prototype with the vacuous-looking declaration struct x; which places an (incomplete) declaration of struct x at file scope, so that all following declarations involving struct x can at least be sure theyre referring to the same struct x.

Is there a way to compare structures automatically? No. There is not a good way for a compiler to implement structure comparison (i.e. to support the == operator for structures) which is consistent with Cs low-level flavor. A simple byte-by-byte comparison could founder on random bits present in unused ``holes in the structure (such padding is used to keep the alignment of later fields correct. A field-by-field comparison might require unacceptable amounts of repetitive code for large structures. Any compiler-generated comparison could not be expected to compare pointer fields appropriately in all cases: for example, its often appropriate to compare char * fields with strcmp rather than ==. If you need to compare two structures, youll have to write your own function to do so, field by field.

Whats the difference between a structure and a union, anyway? A union is essentially a structure in which all of the fields overlay each other; you can only use one field at a time. The size of a union is the maximum of the sizes of its individual members, while the size of a structure is the sum of the sizes of its members. (In both cases, the size may be increased by padding.)

Is there an easy way to print enumeration values symbolically? No. You can write a little function (one per enumeration) to map an enumeration constant to a string, either by using a switch statement or by searching an array. (For debugging purposes, a good debugger should automatically print enumeration constants symbolically.)

Why doesnt this code: a[i] = i++; work? The subexpression i++ causes a side effect--it modifies is value--which leads to undefined behavior since i is also referenced elsewhere in the same expression. There is no way of knowing whether the reference will happen before or after the side effect--in fact, neither obvious interpretation might hold. (Note that although the language in K&R suggests that the behavior of this expression is unspecified, the C Standard makes the stronger statement that it is undefined.)

Why did printf("%d %d", f1(), f2()); call f2 first? I thought the comma operator guaranteed left-to-right evaluation. The comma operator does guarantee left-to-right evaluation, but the commas separating the arguments in a function call are not comma operators. The order of evaluation of the arguments to a function call is unspecified.

People keep saying that the behavior of i = i++ is undefined, but I just tried it on an ANSIconforming compiler, and got the results I expected. A compiler may do anything it likes when faced with undefined behavior (and, within limits, with implementation-defined and unspecified behavior), including doing what you expect. Its unwise to depend on it, though.

Whats the difference between ++i and i++? If your C book doesnt explain, get a better one. Briefly: ++i adds one to the stored value of i and ``returns the new, incremented value to the surrounding expression; i++ adds one to i but returns the prior, unincremented value.

Why doesnt the code int a = 1000, b = 1000; long int c = a * b; work?

Under Cs integral promotion rules, the multiplication is carried out using int arithmetic, and the result may overflow or be truncated before being promoted and assigned to the long int left-hand side. Use an explicit cast on at least one of the operands to force long arithmetic: long int c = (long int)a * b; or perhaps long int c = (long int)a * (long int)b; (both forms are equivalent). Notice that the expression (long int)(a * b) would not have the desired effect. An explicit cast of this form (i.e. applied to the result of the multiplication) is equivalent to the implicit conversion which would occur anyway when the value is assigned to the long int left-hand side, and like the implicit conversion, it happens too late, after the damage has been done.

How can I ensure that integer arithmetic doesnt overflow? The usual approach is to test the operands against the limits in the header file <limits.h> before doing the operation. For example, here is a ``careful addition function: int chkadd(int a, int b) { if(INT_MAX - b < a) { fputs("int overflow\n", stderr); return INT_MAX; } return a + b; }

What are pointers really good for, anyway? Theyre good for lots of things, such as: dynamically-allocated arrays generic access to several similar variables (simulated) by-reference function parameters malloced data structures of all kinds, especially trees and linked lists walking over arrays (for example, while parsing strings) efficient, by-reference ``copies of arrays and structures, especially as function parameters (Note that this is hardly a comprehensive list!)

Does *p++ increment p, or what it points to? The postfix ++ and -- operators essentially have higher precedence than the prefix unary operators. Therefore, *p++ is equivalent to *(p++); it increments p, and returns the value which p pointed to before p was incremented. To increment the value pointed to by p, use (*p)++ (or perhaps ++*p, if the evaluation order of the side effect doesnt matter).

Why cant I perform arithmetic on a void * pointer? The compiler doesnt know the size of the pointed-to objects. (Remember that pointer arithmetic is always in terms of the pointed-to size.) Therefore, arithmetic on void *s is disallowed (though some compilers allow it as an extension). Before performing arithmetic, convert the pointer either to char * or to the pointer type youre trying to manipulate.

Does C even have ``pass by reference? Not really. Strictly speaking, C always uses pass by value. You can simulate pass by reference yourself, by defining functions which accept pointers and then using the & operator when calling, and the compiler will essentially simulate it for you when you pass an array to a function. Another way of looking at it is that if an parameter has type, say, int * then an integer is being passed by reference and a pointer to an integer is being passed by value. Fundamentally, C has nothing truly equivalent to formal pass by reference or C++ reference parameters. (On the other hand, function-like preprocessor macros can provide a form of ``pass by name.)

Whats the total generic pointer type? My compiler complained when I tried to stuff function pointers into a void *. There is no ``total generic pointer type. void *s are only guaranteed to hold object (i.e. data) pointers; it is not portable to convert a function pointer to type void *. (On some machines, function addresses can be very large, bigger than any data pointers.) It is guaranteed, however, that all function pointers can be interconverted, as long as they are converted back to an appropriate type before calling. Therefore, you can pick any function type (usually int (*)() or void (*)(), that is, pointer to function of unspecified arguments returning int or void) as a generic function pointer. When you need a place to hold object and function pointers interchangeably, the portable solution is to use a union of a void * and a generic function pointer (of whichever type you choose

What is this infamous null pointer, anyway? The language definition states that for each pointer type, there is a special value--the ``null pointer--which is distinguishable from all other pointer values and which is ``guaranteed to compare unequal to a pointer to any object or function. That is, a null pointer points definitively nowhere; it is not the address of any object or function. The address-of operator & will never yield a null pointer, nor will a successful call to malloc. (malloc does return a null pointer when it fails, and this is a typical use of null pointers: as a ``special pointer value with some other meaning, usually ``not allocated or ``not pointing anywhere yet.) A null pointer is conceptually different from an uninitialized pointer. A null pointer is known not to point to any object or function; an uninitialized pointer might point anywhere.

What is NULL and how is it defined? As a matter of style, many programmers prefer not to have unadorned 0s scattered through their programs, some representing numbers and some representing pointers. Therefore, the preprocessor macro NULL is defined (by several headers, including <stdio.h> and <stddef.h>) as a null pointer constant, typically 0 or ((void *)0). A programmer who wishes to make explicit the distinction between 0 the integer and 0 the null pointer constant can then use NULL whenever a null pointer is required. Using NULL is a stylistic convention only; the preprocessor turns NULL back into 0 which is then recognized by the compiler, in pointer contexts, as before. In particular, a cast may still be necessary before NULL (as before 0) in a function call argument. NULL should be used only as a pointer constant.

What does a run-time ``null pointer assignment error mean? How can I track it down?

This message, which typically occurs with MS-DOS compilers, means that youve written, via a null pointer, to an invalid location--probably offset 0 in the default data segment. A debugger may let you set some kind of data watchpoint on location 0. Alternatively, you could write a bit of code to stash away a copy of 20 or so bytes from location 0, and periodically check that the memory at location 0 hasnt changed..

Why cant I do something like this? extern char *getpass(); char str[10]; str = getpass("Enter password: "); Arrays are ``second-class citizens in C; one upshot of this prejudice is that you cannot assign to them. When you need to copy the contents of one array to another, you must do so explicitly. In the case of char arrays, the strcpy routine is usually appropriate: strcpy(str, getpass("Enter password: "));

Practically speaking, what is the difference between arrays and pointers? An array is a single, preallocated chunk of contiguous elements (all of the same type), fixed in size and location. A pointer is a reference to any data element (of a particular type) anywhere. A pointer must be assigned to point to space allocated elsewhere, but it can be reassigned (and the space, if derived from malloc, can be resized) at any time. A pointer can point to an array, and can simulate (along with malloc) a dynamically allocated array, but a pointer is a much more general data structure. Due to the so-called equivalence of arrays and pointers, arrays and pointers often seem interchangeable, and in particular a pointer to a block of memory assigned by malloc is frequently treated (and can be referenced using []) exactly as if it were a true array.

How much memory does a pointer variable allocate? Thats a pretty misleading question. When you declare a pointer variable, as in char *p; you (or, more properly, the compiler) have allocated only enough memory to hold the pointer itself; that is, in this case you have allocated sizeof(char *) bytes of memory. But you have not yet allocated any memory for the pointer to point to.

I see code like char *p = malloc(strlen(s) + 1); strcpy(p, s); Shouldnt that be malloc((strlen(s) + 1) * sizeof(char))? Its never necessary to multiply by sizeof(char), since sizeof(char) is, by definition, exactly 1. (On the other hand, multiplying by sizeof(char) doesnt hurt, and in some circumstances may help by introducing a size_t into the expression.)

Why doesnt strcat(string, !); work? There is a very real difference between characters and strings, and strcat concatenates strings. A character constant like ! represents a single character. A string literal between double quotes

usually represents multiple characters. A string literal like "!" seems to represent a single character, but it actually contains two: the ! you requested, and the \0 which terminates all strings in C. Characters in C are represented by small integers corresponding to their character set values. Strings are represented by arrays of characters; you usually manipulate a pointer to the first character of the array. It is never correct to use one when the other is expected. To append a ! to a string, use strcat(string, "!");

Whats the difference between const MAXSIZE = 100; and #define MAXSIZE 100 A preprocessor #define gives you a true compile-time constant. In C, const gives you a run-time object which youre not supposed to try to modify; ``const really means ``readonly. (But in C++, const is closer to #define.)

Is it acceptable for one header file to #include another? Its a question of style, and thus receives considerable debate. Many people believe that ``nested #include files are to be avoided: the prestigious Indian Hill Style Guide disparages them; they can make it harder to find relevant definitions; they can lead to multiple-definition errors if a file is #included twice; they can lead to increased compilation time; and they make manual Makefile maintenance very difficult. On the other hand, they make it possible to use header files in a modular way (a header file can #include what it needs itself, rather than requiring each #includer to do so); a tool like grep (or a tags file) makes it easy to find definitions no matter where they are; a popular trick along the lines of: #ifndef HFILENAME_USED #define HFILENAME_USED ...header file contents... #endif (where a different bracketing macro name is used for each header file) makes a header file ``idempotent so that it can safely be #included multiple times; a clever compiler can avoid expending any more time on later instances of an already-included header; and automated Makefile maintenance tools (which are a virtual necessity in large projects anyway) handle dependency generation in the face of nested #include files easily.

Whats the difference between #include <> and #include "" ? The <> syntax is typically used with Standard or system-supplied headers, while "" is typically used for a programs own header files.

What are the complete rules for header file searching? The exact behavior is implementation-defined (which means that it is supposed to be documented). Typically, headers named with <> syntax are searched for in one or more standard places. Header files named with "" syntax are first searched for in the ``current directory, then (if not found) in the same standard places. (This last rule, that "" files are additionally searched for as if they were <> files, is the only rule specified by the Standard.) Another distinction is the definition of ``current directory for "" files. Traditionally (especially under Unix compilers), the current directory is taken to be the directory containing the file containing the #include directive. Under other compilers, however, the current directory is the directory in which the compiler was initially invoked. (Compilers running on systems without

directories or without the notion of a current directory may of course use still different rules.) It is also common for there to be a way (usually a command line option involving capital I, or maybe an environment variable) to add additional directories to the list of standard places to search. Check your compiler documentation.

How can inline functions help with the tradeoff of safety vs. speed? In straight C, you can achieve "encapsulated structs" by putting a void* in a struct, in which case the void* points to the real data that is unknown to users of the struct. Therefore users of the struct dont know how to interpret the stuff pointed to by the void*, but the access functions cast the void* to the appropriate hidden type. This gives a form of encapsulation. Unfortunately it forfeits type safety, and also imposes a function call to access even trivial fields of the struct (if you allowed direct access to the structs fields, anyone and everyone would be able to get direct access since they would of necessity know how to interpret the stuff pointed to by the void*; this would make it difficult to change the underlying data structure). Function call overhead is small, but can add up. C++ classes allow function calls to be expanded inline. This lets you have the safety of encapsulation along with the speed of direct access. Furthermore the parameter types of these inline functions are checked by the compiler, an improvement over Cs #define macros.

Should I explicitly call a destructor on a local variable? No! The destructor will get called again at the close } of the block in which the local was created. This is a guarantee of the language; it happens automagically; theres no way to stop it from happening. But you can get really bad results from calling a destructor on the same object a second time! Bang! Youre dead!

When I throw this object, how many times will it be copied? Depends. Might be "zero." Objects that are thrown must have a publicly accessible copy-constructor. The compiler is allowed to generate code that copies the thrown object any number of times, including zero. However even if the compiler never actually copies the thrown object, it must make sure the exception classs copy constructor exists and is accessible.

Is there any difference between List x; and List x();? big difference! Suppose that List is the name of some class. Then function f() declares a local List object called x: void f() { List x; // Local object named x (of class List) ... } But function g() declares a function called x() that returns a List: void g() { List x(); // Function named x (that returns a List) ... } Is the default constructor for Fred always Fred::Fred()? No. A "default constructor" is a constructor that can be called with no arguments. One example of

What are the 3 cases considered while deleting the nodes from the linklist? Case 1: CurrentNode = Head Node In this case, the node to be deleted is actually the Head node. This is a special case because there is no previous node to connect. We simply use our temp pointer to remember where Head is pointing at, advance the Head to the next position, then delete our saved location! Case 2: CurrentNode = End node In this case, the node to be deleted is actually the Tail node. This is a special case because we have a previous node, but no node afterwards to connect to. We save the old location of Tail using temp, set Tail equal to the previous node, set the Next pointer of Tail equal to NULL since it is at the end, then delete our temp pointer. Case 3: CurrentNode is somewhere in between In this case, there is a node before and a node after our current node. All we need to do is connect the previous node to the node after our current node. We set temp equal to our previous node and set the Next pointer to the node after our current one (corpse). Once they are connected, we can simply delete our current pointer.

What are the elementary functions in Linklist? A linked list class should contain the following elementary functions: Add To Head (Var_Type element) Add To Tail (Var_Type element) Var_Type Remove From Head Var_Type Remove From Tail

What is the way to point to the LinkedDeque? struct Node { // a node in the deque Object element; // element Node* prev; // previous node Node* next; // next node Node(const Object& e = Object(), Node* p = NULL, Node* n = NULL) : element(e), prev(p), next(n) { } // constructor }; typedef Node* NodePtr; // pointer to node

What are the two methods of implementing the queues? Approach one : We initialize " Front = 0 " , and " Rear = -1 " ; and the test for empty queue " Front = = NextPosition(Rear) ? " . But `the main problem here is that this condition also holds for a full queue. Increase rear then put the value. Front points to the first element. Rear points to the last element. Approach two : We check " Front = = Rear ?" which indicates an empty queue. Front points to a never used item, and real data starts from the next position to the front. Front must always points to an empty cell, and this means that well lose a place in memory (never used cell) but on the other hand its make it easier to detect an empty queue .

What are the different ways to traverse Binary Tree? PREORDER: 1) Visit the root. 2) Transverse the left leaf in preorder. 3) Transverse the right leaf in preorder. INORDER: 1) Transverse the left leaf in inorder. 2) Visit the root. 3) Transverse the right leaf in inorder. POSTORDER: 1) Transverse the left leaf in postorder. 2) Transverse the right leaf in postorder. 3) Visit the root.

How do I get scrolling text in the status bar? This is not an HTML question, its done with a Javascript. Check any page which has this feature, and copy the script from the source. These scripts have two big problems. First, usually it uses the decrement operator (c--) at some point. The "--" sequence in a comment actually closes it on some browsers, so your code may "leak" on those browsers. The same goes for ">". Second, keep in mind that many people consider this even worse than <BLINK>, and that it also suppresses the status information which normally appears there. It prevents people from knowing where a link goes to.

How do I hide my source? You cant. The source is necessary for the browser to display your document. You have to send the complete, unencrypted source to the browser. Even if a particular browser doesnt have a "View source" option, there are many that do, and you can always retrieve the document by hand (using telnet) to get its source. Or check the browsers cache. You can of course put a few hundred empty lines above the actual source, then newbies who dont see the scrollbars will think there is nothing there.

How do I get my visitors e-mail addresses? You cant. Although each request for a document is usually logged with the name or address of the remote host, the actual username is almost never logged as well. This is mostly because of performance reasons, as it would require that the server uses the ident protocol to see who is on the other end. This takes time. And if a cache proxy is doing the request, you dont get anything sensible. The most reliable way is to put up a form, asking the visitor to fill in his e-mail address. If you offer him something in return, he will most likely do it.

Is there a way to get indexed better by the search engines? The best way is to provide good content and to avoid any tricks like repeatedly including the same keywords, or putting keywords in white-text-on-white-background to fool search engines. And get links from other sites. That increases your popularity and hence your position in the search results. In the past you could use the META tag "keywords" to suggest extra keywords. This no longer works, because it has been heavily abused. You can however still use: <META NAME="description" CONTENT="description of your site"> This allows you to suggest a descriptive text that a search engine could show if this page is found in a search. You can put up to 1022 characters in the CONTENT attribute.

How do I redirect someone to my new page? The most reliable way is to configure the server to send out a redirection instruction when the old URL is requested. Then the browser will automatically get the new URL. This is the fastest way to do this. You can of course also simply put up a small page with a text like "This page has moved to http://new.url/, please adjust your bookmarks".

What are the system requirements for windows 2003 server? Requirement s:- Minimum CPU Speed Standard Edition 133 MHz Enterprise Edition 133 MHz for x86-based computers 733 MHz for Itanium-based computers Datacenter Edition 400 MHz for x86-based computers 733 MHz for Itanium-based computers Web Edition 133 MHz Requirement Recommended CPU Speed Standard Edition 550 MHz Enterprise Edition 733 MHz Datacenter Edition 733 MHz Web Edition 550 MHz Requirement Minimum RAM Standard Edition 128 MB Enterprise Edition 128 MB Datacenter Edition 512 MB Web Edition 128 MB Requirement Recommended Minimum RAM Standard Edition 256 MB Enterprise Edition 256 MB Datacenter Edition 1 GB Web Edition 256 MB Requirement Maximum RAM Standard Edition 4 GB Enterprise Edition 32 GB for x86-based computers 512 GB for Itanium-based computers Datacenter Edition 64 GB for x86-based computers 512 GB for Itanium-based computers Web Edition 2 GB Requirement Multiprocessor Support Standard Edition Up to 4 Enterprise Edition Up to 8 Datacenter Edition Minimum 8 required Maximum 64 Web Edition Up to 2 Requirement Disk Space for Setup Standard Edition 1.5 GB Enterprise Edition 1.5 GB for x86-based computers 2.0 GB for Itanium-based computers Datacenter Edition 1.5 GB for x86-based computers 2.0 GB for Itanium-based computers Web Edition 1.5 GB

How many different versions of Windows Server 2003 are there?

There are six versions of Windows server 2003. they are as follows: 1. Windows Server 2003 Web Server This edition supports only up to 2GB Ram and is restricted for use in a webhosting environment. 2. Windows Server 2003 Standard Server This edition is for small and medium businesses. This edition replaced Windows 2000 Server. 3. Windows Server 2003 Enterprise Server This edition is for medium and large businesses. This edition replaced Windows 2000 Advanced Server. 4. Windows Server 2003 Datacenter Server This edition is aimed for high end servers and supports up to 64 processors. This edition replaced Windows 2000 Datacenter Server. 5. Windows Server 2003 Compute Cluster Edition This is an edition of Windows Server 2003 for clusters and supercomputers. 6. Windows Small Business Server 2003 Small Business Server 2003 is aimed for small businesses and have (license) restriction over the other Windows Server 2003 products.

Which sequences are contained in boot process? The boot sequence consists of the following sequences: 1. Pre boot sequence 2. Boot sequence 3. Kernel load sequence 4. Kernel initialization sequence 5. Logon sequence 6. Plug-and-play device detection phase

How to activate the TELNET service? The service is disabled by default. You can modify start state and start it from the Services applet, or from a console use the following: sc config TlntSvr start= auto net start TlntSvr

What are the various user profiles provided by Windows 2003? Windows Server 2003 provides three types of user profiles: 1. Local user profile: It is created by default when a user logs on to a system for the first time. The local user profile is the default user profile, which means that if the user logs on from any other computer. 2. Roaming user profile: In a roaming user profile folder is saved on the server. This ensures that the user profile remains consistent, and the user profile folder remains available, even when the

user logs on from the different computers. 3. Mandatory user profiles: It is like the roaming user profile, the user profile folder is saved at a central location. In this case, if the user makes changes in the settings, the changes are not saved on the server, and the user profile remains consistent.

What steps should be performed, if a user is unable to logon to system? Perform the following steps, in case you are not able to logon to a system: 1. In many cases you might be using the wrong user name, password, or domain name. In such cases, reset the password in Active Directory Users and Computers console. 2. Ensure that the global catalog server is available at the time you are logging in a multiple-domain environment for the first time. 3. Ensure that you have sufficient rights in the default Domain Controllers policy when you try to log on to a domain controller. 4. Ensure that global catalog server is available to service the request if you are attempting to log on using a UPN.

How to verify that a computer account in windows 2003 server is disabled? To verify that a computer account is disabled, just check in the right pane of the Active Directory of users and Computers window, observe that the computer account is displayed with a red Cross mark indicating that the computer account is disabled.

What steps need to be done if the sound of system does not work and if all drivers are installed and the Device Manager reports it is working properly? In such a case, the windows audio service needs to be enabled. To enable it: 1. Click Start, then Run, and type "services.msc" (without quotes) and click OK. 2. Find the "Windows Audio" service (without quotes), right click and select Properties, select "Automatic" instead of "Disabled" (without quotes) in the startup type box 3. Click Apply. 4. Click Start 5. Click OK.

Why DirectX acceleration doesnt work in Windows Server 2003? This is by design. Graphics Acceleration is disabled by default, which disables DirectX functionality. This is to enhance server stability and is not needed in standard server scenarios. Re-enabling such functionality is not a valid server testing scenario.

What are Special Identities? Windows Server 2003 supports some special groups called as Special Identities. Special Identities are

created and managed by Windows server 2003. As a result, system administrators cannot create or delete special identities. In addition system administrators cannot modify the membership of special identities. For example, Network is a special identity which includes users who are currently accessing a resource over a network.

What are the technologies or tools that have been enhanced from the earlier version of SQL Server, i.e. SQL Server 2000? Almost all the different tools have been enhanced, some to a greater extent and some less. The tools that have been enhanced to a greater extent are 1. Database Engine 2. Analysis services 3. DTS 4. Database administration tools 5. XML Support 6. ADO.NET

What are the enhancements done to the database engine? The following are the new features in the database engine. 1. The integration of .NET runtime in to the database has lead to the addition of new key words to the existing set of keywords to T-SQL. These keywords mainly communicate the CLR related tasks to the database engine. 2. XML is a new datatype that could represent any xml. 3. TRY and CATCH are the new constructs that are available with SQL Server 2005 for handling the exception conditions in T-SQL statements. This fulfills the long required need for a good mechanism to handle errors in the stored procedures. 4. Now a DBA can create a Full Text catalog using the new keyword CREATE FULLTEXT CATALOG, unlike the earlier sp_fulltext catalog. In addition easier handling of the fulltext catalog by having keywords for attaching the detaching the catalogs. 5. New relational operators such as PIVOT, UNPIVOT, and APPLY to get complex information form the database. 6. Persisted Computed columns is supported in SQL Server 2005.

What are the enhancements in Analysis Services? The following are the new enhancements to the Analysis services. 1. The user interface for the analysis services have been drastically changed. Now there is a project based development for a specific Business Intelligence task. The new UI features new wizard driven tasks. 2. The cubes now provide customizable business metrics called Key Performance Indicators (KPI) that would assist in tracking performance leading to improved decision making abilities. 3. Microsoft adds a new algorithm, which (Naive Bayes) is a classification algorithm this is quick to build and works well for predictive modeling. 4. Object Definition Language is an XML language which allows a user to create, modify and delete Analysis Services Objects. This now enables a developer to perfom functions on the Analysis Server by just sending XML messages. 5. ADOMD.NET (ADO Multi Dimension) is the new standard .NET Data provider that is designed to communicate with multidimensional data sources.

What are the enhancements in Data Transformation Services (DTS)? The new DTS designer is now integrated into the Microsoft Visual Studio Development Environment, which now provides one single integrated development experience to perform Data transformation functions with SQL Server 2005. This now enables and integrates with SourceSafe for version control. The new DTP engine now provides support for data flow between multiple sources, multiple transformations and multiple destinations. Now the new engine supports several new transformations such as Multicast Transformation, Conditional Split Transformation, Sort and Lookup Transformation etc. Long needed deployment mechanism is featured in SQL Server 2005. Now a DTS package can be

What is PL/SQL and what is it used for? PL/SQL is Oracles Procedural Language extension to SQL. PL/SQLs language syntax, structure and data types are similar to that of ADA. The PL/SQL language includes object oriented programming techniques such as encapsulation, function overloading, and information hiding (all but inheritance). PL/SQL is commonly used to write data-centric programs to manipulate data in an Oracle database.

Should one use PL/SQL or Java to code procedures and triggers? Internally the Oracle database supports two procedural languages, namely PL/SQL and Java. This leads to questions like "Which of the two is the best?" and "Will Oracle ever desupport PL/SQL in favour of Java? Many Oracle applications are based on PL/SQL and it would be difficult of Oracle to ever desupport PL/SQL. In fact, all indications are that PL/SQL still has a bright future ahead of it. Many enhancements are still being made to PL/SQL. For example, Oracle 9iDB supports native compilation of Pl/SQL code to binaries. PL/SQL and Java appeal to different people in different job roles. The following table briefly describes the difference between these two language environments: PL/SQL: Data centric and tightly integrated into the database. Proprietary to Oracle and difficult to port to other database systems. Data manipulation is slightly faster in PL/SQL than in Java. Easier to use than Java (depending on your background). Java: Open standard, not proprietary to Oracle. Incurs some data conversion overhead between the Database and Java type systems. Java is more difficult to use (depending on your background).

How can one see if somebody modified any code? Code for stored procedures, functions and packages is stored in the Oracle Data Dictionary. One can detect code changes by looking at the LAST_DDL_TIME column in the USER_OBJECTS dictionary view. Example: SELECT OBJECT_NAME, TO_CHAR(CREATED, DD-Mon-RR HH24:MI) CREATE_TIME, TO_CHAR(LAST_DDL_TIME, DD-Mon-RR HH24:MI) MOD_TIME, STATUS FROM USER_OBJECTS WHERE LAST_DDL_TIME > &CHECK_FROM_DATE;

How can one search PL/SQL code for a string/ key value? The following query is handy if you want to know where a certain table, field or expression is referenced in your PL/SQL source code. SELECT TYPE, NAME, LINE FROM USER_SOURCE WHERE UPPER(TEXT) LIKE %&KEYWORD%;

How can one keep a history of PL/SQL code changes? One can build a history of PL/SQL code changes by setting up an AFTER CREATE schema (or database) level trigger (available from Oracle 8.1.7). This way one can easily revert to previous code should someone make any catastrophic changes. Look at this example: CREATE TABLE SOURCE_HIST -- Create history table AS SELECT SYSDATE CHANGE_DATE, USER_SOURCE.* FROM USER_SOURCE WHERE 1=2; CREATE OR REPLACE TRIGGER change_hist -- Store code in hist table AFTER CREATE ON SCOTT.SCHEMA -- Change SCOTT to your schema name DECLARE BEGIN if DICTIONARY_OBJ_TYPE in (PROCEDURE, FUNCTION, PACKAGE, PACKAGE BODY, TYPE) then -- Store old code in SOURCE_HIST table INSERT INTO SOURCE_HIST SELECT sysdate, user_source.* FROM USER_SOURCE WHERE TYPE = DICTIONARY_OBJ_TYPE AND NAME = DICTIONARY_OBJ_NAME; end if; EXCEPTION WHEN OTHERS THEN raise_application_error(-20000, SQLERRM); END; / show errors

Can one print to the screen from PL/SQL? One can use the DBMS_OUTPUT package to write information to an output buffer. This buffer can be displayed on the screen from SQL*Plus if you issue the SET SERVEROUTPUT ON; command. For example: set serveroutput on begin dbms_output.put_line(Look Ma, I can print from PL/SQL!!!); end; / DBMS_OUTPUT is useful for debugging PL/SQL programs. However, if you print too much, the output buffer will overflow. In that case, set the buffer size to a larger value, eg.: set serveroutput on size 200000 If you forget to set serveroutput on type SET SERVEROUTPUT ON once you remember, and then EXEC NULL;. If you havent cleared the DBMS_OUTPUT buffer with the disable or enable procedure, SQL*Plus will display the entire contents of the buffer when it executes this dummy PL/SQL block. Note that DBMS_OUTPUT doesnt print blank or NULL lines. To overcome this problem, SET SERVEROUTPUT ON FORMAT WRAP; Look at this example with this option first disabled and then enabled: SQL> SET SERVEROUTPUT ON SQL> begin 2 dbms_output.put_line(The next line is blank); 3 dbms_output.put_line(); 4 dbms_output.put_line(The above line should be blank);

5 end; 6/ The next line is blank The above line should be blank SQL> SET SERVEROUTPUT ON FORMAT WRAP SQL> begin 2 dbms_output.put_line(The next line is blank); 3 dbms_output.put_line(); 4 dbms_output.put_line(The above line should be blank); 5 end; 6/ The next line is blank The above line should be blank

Can one call DDL statements from PL/SQL? One can call DDL statements like CREATE, DROP, TRUNCATE, etc. from PL/SQL by using the "EXECUTE IMMEDATE" statement. Users running Oracle versions below 8i can look at the DBMS_SQL package. begin EXECUTE IMMEDIATE CREATE TABLE X(A DATE); end; NOTE: The DDL statement in quotes should not be terminated with a semicolon.

Can one use dynamic SQL statements from PL/SQL? Starting from Oracle8i one can use the "EXECUTE IMMEDIATE" statement to execute dynamic SQL and PL/SQL statements (statements created at run-time). Look at these examples. Note that statements are NOT terminated by semicolons: EXECUTE IMMEDIATE CREATE TABLE x (a NUMBER); -- Using bind variables... sql_stmt := INSERT INTO dept VALUES (:1, :2, :3); EXECUTE IMMEDIATE sql_stmt USING dept_id, dept_name, location; -- Returning a cursor... sql_stmt := SELECT * FROM emp WHERE empno = :id; EXECUTE IMMEDIATE sql_stmt INTO emp_rec USING emp_id; One can also use the older DBMS_SQL package (V2.1 and above) to execute dynamic statements. Look at these examples: CREATE OR REPLACE PROCEDURE DYNSQL AS cur integer; rc integer; BEGIN cur := DBMS_SQL.OPEN_CURSOR; DBMS_SQL.PARSE(cur, CREATE TABLE X (Y DATE), DBMS_SQL.NATIVE); rc := DBMS_SQL.EXECUTE(cur); DBMS_SQL.CLOSE_CURSOR(cur); END; /

More complex DBMS_SQL example using bind variables: CREATE OR REPLACE PROCEDURE DEPARTMENTS(NO IN DEPT.DEPTNO%TYPE) AS v_cursor integer; v_dname char(20); v_rows integer; BEGIN v_cursor := DBMS_SQL.OPEN_CURSOR; DBMS_SQL.PARSE(v_cursor, select dname from dept where deptno > :x, DBMS_SQL.V7); DBMS_SQL.BIND_VARIABLE(v_cursor, :x, no); DBMS_SQL.DEFINE_COLUMN_CHAR(v_cursor, 1, v_dname, 20); v_rows := DBMS_SQL.EXECUTE(v_cursor); loop if DBMS_SQL.FETCH_ROWS(v_cursor) = 0 then exit; end if; DBMS_SQL.COLUMN_VALUE_CHAR(v_cursor, 1, v_dname); DBMS_OUTPUT.PUT_LINE(Deptartment name: ||v_dname); end loop; DBMS_SQL.CLOSE_CURSOR(v_cursor); EXCEPTION when others then DBMS_SQL.CLOSE_CURSOR(v_cursor); raise_application_error(-20000, Unknown Exception Raised: ||sqlcode|| ||sqlerrm); END; /

What is the difference between %TYPE and %ROWTYPE? The %TYPE and %ROWTYPE constructs provide data independence, reduces maintenance costs, and allows programs to adapt as the database changes to meet new business needs. %ROWTYPE is used to declare a record with the same types as found in the specified database table, view or cursor. Example: DECLARE v_EmpRecord emp%ROWTYPE; %TYPE is used to declare a field with the same type as that of a specified tables column. Example: DECLARE v_EmpNo emp.empno%TYPE;

What is the result of comparing NULL with NULL? NULL is neither equal to NULL, nor it is not equal to NULL. Any comparison to NULL is evaluated to NULL. Look at this code example to convince yourself. declare a number := NULL; b number := NULL; begin if a=b then dbms_output.put_line(True, NULL = NULL); elsif a<>b then dbms_output.put_line(False, NULL <> NULL);

else dbms_output.put_line(Undefined NULL is neither = nor <> to NULL); end if; end;

C - A "Programming language" OR an "Intermediate language"! C has facilities for structured programming and allows lexical variable scope and recursion. Parameters of C functions are always passed by value. Pass-by-reference is achieved in C by explicitly passing pointer values. C program source text is free-format, using semicolon as a statement terminator (not a delimiter). A simple program in C as follows:#include <stdio.h> int main(void) { printf("hello, world\n"); return 0; } C is used as an intermediate language by some higher-level languages. This is implemented in one of two ways, as languages which: 1. Emit C source code, and one or more other representations: machine code, object code, and/or byte codes. Examples: some dialects of Lisp (Lush, Gambit), Squeaks C-subset Slang. 2. Emit C source code only, and no other representation. Examples: Eiffel, Sather, Esterel, and Vala. C source code is then input to a C compiler, which then outputs finished machine or object code. This is done to gain portability (C compilers exist for nearly all platforms) and to avoid having to develop machine-specific code generators.

The dimension of character string is always defined to be larger than maximum number of characters required to store in the array. When a character string is declared,the last element in a character array is reserved,by convention,to store the string terminator character \0.So,the dimension of character string is always defined to be larger than maximum number of characters required to store in the array,so as to take care of string terminator.

Conditional Compilation in C! In C, compiler can skip over a part of a source code by inserting the preprocessing commands #ifdef and #endif which have general form as: #ifdef macroname statement1; statement2; statement3; #endif If a macroname has been defined #ifdef then it will not get processed. Now, when we need to compile only a part of program. There are two cases: 1.It often happens that a program is need to be changed at the last minute, to satisfy a client. This involves rewriting some part of source code to the clients satisfaction and delete the old code. But then it may happen that this code can be required by some other application. In such case, we can write this code in between #ifdef and #endif directives, and remove them whenever the code required.

<iostream.h> or <iostream>? Many C++ programmers still use <iostream.h> instead of the newer, standard compliant <iostream> library. What are the differences between the two? First, the .h notation of standard header files was deprecated more than five years ago. Using deprecated features in new code is never a good idea. In terms of functionality, <iostream> contains a set of templatized I/O classes which support both narrow and wide characters, as opposed to <iostream.h> which only supports char-oriented streams. Third, the C++ standard specification of iostreams interface was changed in many subtle aspects. Consequently, the interfaces and implementation of <iostream> differ from those of <iostream.h>. Finally, <iostream> components are declared in namespace std whereas <iostream.h> components are global. Because of these substantial differences, you cannot mix the two libraries in one program. As a rule, use <iostream> unless youre dealing with legacy code that is only compatible with <iostream.h>.

Comma-Separated Expressions Comma-separated expressions were inherited from C. Its likely that you use such expressions in forand while-loops rather often. Yet, the language rules in this regard are far from being intuitive. First, lets see what a comma separated expression is. An expression may consist of one or more sub-expressions separated by commas. For example: if (++x, --y, cin.good ()) /*three expressions*/ The if condition contains three expressions separated by commas. C++ ensures that each of the expressions is evaluated and its side effects take place. However, the value of an entire commaseparated expression is only the result of the rightmost expression. Therefore, the if condition above evaluates as true only if cin.good () returns true. Heres another example of a comma expression: int j=10; int i=0; while( ++i, --j) { /*..repeat as long as j is not 0*/ }

Why Inheriting from a Class That Has No Virtual Destructor is Dangerous Classes with a non-virtual destructor arent meant to serve as base classes (such classes are usually known as "concrete classes"). std::string, std::complex, and std::vector are concrete classes. Why is inheriting from such classes not recommended? When you use public inheritance, you create an is-a relationship between the base class and its derived classes. Consequently, pointers and references to base can actually point to a derived object. Because the destructor isnt virtual, C++ will not call the entire destructor chain when you delete such an object. For example: class A { public: ~A() // non virtual { // ... } }; class B: public A /* bad; A has a non virtual dtor*/

How is Stack implemented as a class? # include<iostream.h> # include<process.h> # include<conio.h> # define SIZE 20 class stack{ int a[SIZE]; int tos; // Top of Stack public: stack(); void push(int); int pop(); int isempty(); int isfull();}; stack::stack(){ tos=0; //Initialize Top of Stack} int stack::isempty(){ return (tos==0?1:0); } int stack::isfull() { return (tos==SIZE?1:0);} void stack::push(int i) { if(!isfull()) { a[tos]=i; tos++; } else { cerr<<"Stack overflow error !\nPossible Data Loss !"; } } int stack::pop() { if(!isempty()) { return(a[--tos]); } else { cerr<<"Stack is empty! What to pop...!"; } return 0; } void main() { stack s; int ch=1,num; while(ch!=0) { cout<<"Stack Operations Mani Menu\n1.Push\n2.Pop\n3.IsEmpty\ 4.IsFull\n0.Exit\n\n"; cin>>ch; switch(ch) { case 0: exit(1); //Normal Termination of Program case 1: cout<<"Enter the number to push"; cin>>num; s.push(num); break; case 2: cout<<"Number popped from the stack is: "<<s.pop()<<endl; break; case 3: (s.isempty())?(cout<<"Stack is empty.\n"): (cout<<"Stack is not empty.\n"); break; case 4: (s.isfull())?(cout<<"Stack is full.\n"): (cout<<"Stack is not full.\n"); break; default: cout<<"Illegal Option.\nPlease try again\n"; } }//end of while getch(); }

How can you implement Queues as a Class? # include<iostream.h> # include<conio.h> # define SIZE 20 class queue { int a[SIZE],front, rear; public: queue(); ~queue(); void insert(int i); int remove(); int isempty(); int isfull(); }; queue::queue(){ front=0; rear=0; } queue::~queue(){ delete []a; } void queue::insert(int i) { if(isfull()){ cout<<"\n\n******\nQueue is FULL !!!\nNo insertion allowed further.\n******\n"; return; } a[rear] = i; rear++; } int queue::remove() { if(isempty()) { cout<<"\n\n******\nQueue Empty !!!\nValue returned will be garbage.\n******\n"; return (-9999); } return(a[front++]); } int queue::isempty() { if(front == rear) return 1; else return 0; } int queue::isfull() { if(rear == SIZE) return 1; else return 0; } void main() { clrscr(); queue q; q.insert(1); q.insert(2); cout<<"\n"<<q.remove(); cout<<"\n"<<q.remove(); cout<<"\n"<<q.remove(); getch(); }

How can you add the node in Linklist? You can add the node in the beginning or the end, although the standard seems to be the end. This makes our linked list act kind of like a que with the head node being the oldest and end pointing to the newest objects. void SLList::AddANode() { Tail->Next = new List; Tail=Tail>Next; }

How can you remove an element from the head of a linked list? // Remove an element from the head of the linked list procedure RemoveFromHead():integer if(this is the Head) element = head->info temp = head if(this is the last item in the list) Break pointer connection between head and tail to terminate list else set head.next to equal next item in list end if release temp from from memory pool return element else return 0 end if end procedure

How can you delete an item from the Heap? int HeapClass::Delete(void) { int Temp; if (HeapSize == 0) { cerr << "Cannot remove from an empty heap" << endl; exit(1); } Temp = HeapArrayPtr[0]; // Item at index 0 is the smallest // copy last one to root: HeapArrayPtr[0] = HeapArrayPtr[HeapSize - 1]; HeapSize--;

I want pretty graphics, not black dots for my bullet list! The easiest way to do it is with the definition list tags. This involves opening the list with <DL>, surrounding each member line with the <DD> and </DD> tags, and finishing the list with the </DL> tag. Example: This is the first item This is the second item This is a very long line. It is to show you what happens when we get to the end of our screen. If all goes well, the wrapped part should start directly under the first character of the line above it. Huh? It doesnt? Oh well, the price of vanity... Source: <DL> <DD><IMG SRC="/graphics/bullets/40-99-20.gif">This is the first item</DD> <DD><IMG SRC="/graphics/bullets/40-80-99.gif">This is the second item</DD> <DD><IMG SRC="/graphics/bullets/40-99-20.gif"> This is a very long line. It is to show you what happens when we get to the end of our screen. If all goes well, the wrapped part should start directly under the first character of the line above it. Huh? It doesnt? Oh well, the price of vanity...</DD> </DL>

I need to set up an outline list, but I do not want to have to renumber and re-letter everything when I add, delete or insert new information. There are going to be times when you need to present your information in outline format. Since the Web has some academic roots, it comes already setup to do this. You may have already used the Unordered List using the <UL> tags. To do the Ordered List, you guessed it. We use the <OL> tags! If you look at the example below, you will see that I have taken the outline down to four levels. The format of this tag is very simple. <OL TYPE=I> tells the browser to start numbering with I <OL TYPE=A> tells the browser to start numbering with A <OL TYPE=a> tells the browser to start numbering with a <OL TYPE=i> tells the browser to start numbering with i <OL TYPE=1> tells the browser to start numbering with 1 Each list nest or level is closed with the </OL> tag. The tricky part is remembering where you are as you nest the items of your outline. I strongly urge you to indent! Example: I. This is the first entry of the first level TYPE=I A. This would be the first of the second level TYPE=A B. This would be the second of the second level TYPE=A a. This would be the first of the third level TYPE=a b. This would be the second of the third level TYPE=a i. Now we are four levels deep TYPE=i ii. Another one just for artistic purposes TYPE=i II. This is the second entry of the first level TYPE=I A. Now we start a new set under here. TYPE=A Source Code: <OL TYPE=I> <LI>This is the first entry of the first level TYPE=I

<OL TYPE=A> <LI>This would be the first of the second level TYPE=A <LI>This would be the second of the second level TYPE=A <OL TYPE=a> <LI>This would be the first of the third level TYPE=a <LI>This would be the second of the third level TYPE=a <OL TYPE=i> <LI>Now we are four levels deep TYPE=i <LI>Another one just for artistic purposes TYPE=i </OL> </OL> </OL> <LI>This is the second entry of the first level TYPE=I <OL TYPE=A> <LI>Now we start a new set under here. TYPE=A </OL> </OL>

How can I create tables with vivid colors with no spaces or lines between them? Source Code : <TABLE WIDTH="550" CELLPADDING=0 CELLSPACING=0 BORDER=0 BGCOLOR="#000000"> <TR> <TD> <CENTER> <FONT SIZE="3" COLOR="#EEEEEE" FACE="ARIAL"> <B>THIS TABLE IS OUR TITLE AREA</B></FONT> </CENTER> </TD> </TR> </TABLE> <TABLE CELLPADDING=0 BORDER=0 CELLSPACING="0" WIDTH="550" BGCOLOR="#66FFCC"> <TR> <TD> <FONT FACE="ARIAL"> &nbsp;<BR> In this example, the black region above is one table, and this table contains this text. By setting CELLPADDING, BORDER, and CELLSPACING all to 0 (ZERO), I can get a clean result! <BR> &nbsp; <BR> </FONT> </TD> </TR> </TABLE>

Why when I create a table with empty cells do I get what looks like a raised or miscolored cell where there is no data? As with many things in HTML, there is not what I consider to be a logical reason for this particular behavior. The trick around it is to stick into the empty cell an invisible or non-printable character.

The favorite for this purpose is &nbsp; Please look carefully at the source code . You will notice that the first table created through the first source code given below has a problem, and the second does not. If you get a chance, view this page with both Netscape and MS Internet Explorer and you will see a difference in how the browsers handle the first table! Source code for table with empty cell problem <TABLE WIDTH=230 BORDER=1 BGCOLOR=#00FFFF> <TR> <TD BGCOLOR=#00FF00 COLSPAN=2 ALIGN=CENTER> Table Containing True Empty Cells </TD> </TR> <TR> <TD WIDTH=115>This cell has text</TD> <TD WIDTH=115></TD> </TR> <TR> <TD WIDTH=115></TD> <TD WIDTH=115>This cell has text</TD> </TR> </TABLE> Source code for table without empty cell problem <TABLE WIDTH=230 BORDER=1 BGCOLOR=#00FFFF> <TR> <TD BGCOLOR=#00FF00 COLSPAN=2 ALIGN=CENTER> Table with Hidden Characters in Empty Cells </TD> </TR> <TR> <TD WIDTH=115>This cell has text</TD> <TD WIDTH=115>&nbsp;</TD> </TR> <TR> <TD WIDTH=115>&nbsp;</TD> <TD WIDTH=115>This cell has text</TD> </TR> </TABLE>

Is there a way that I can create a link using text, but not have it underlined? Believe it or not, yes you can. Its strongly recommend that you consider exactly how you should use it. A reader may not realize you have created a link unless you are pretty obvious about it. This works with MSIE and Netscape Communicator. Source code: <A HREF="./example.html" STYLE="TEXT-DECORATION: NONE"> I AM REALLY A LINK!</A> ________________________________________ You can also turn off link underlining on an entire page

by placing the following code near the top of your page, just over the <BODY> and <HEAD> tags. <STYLE TYPE="text/css"> <!-A {text-decoration: none} --> </STYLE>

How to Select between the SQL Server Recovery Model? You can select the Simple if: 1) Your data is not critical. 2) Losing all transactions since the last full or differential backup is not an issue. 3) Data is derived from other data sources and is easily recreated. 4) Data is static and does not change often. 5) Space is limited to log transactions. (This may be a short-term reason, but not a good long-term reason.) You can select Bulk-Logged if: 1) Data is critical, but logging large data loads bogs down the system. 2) Most bulk operations are done off hours and do not interfere with normal transaction processing. 3) You need to be able to recover to a point in time. You can select Full if: 1) Data is critical and no data can be lost. 2) You always need the ability to do a point-in-time recovery. 3) Bulk-logged activities are intermixed with normal transaction processing. 4) You are using replication and need the ability to resynchronize all databases involved in replication to a specific point in time.

How to implement your backup model? You can run backups manually,but the best approach is to schedule backups using SQL Agent. Once you set up the backup job, let SQL Agent run the backups on a set schedule. This can be done by the following ways: 1) Enterprise Manager a) Right click on the database name. b) Select "All Tasks." c) Select "Backup Database." d) Once the options are set, you can then use the schedule option to create a job. 2) T-SQL a) Using BACKUP commands, you can create the command and then use Enterprise Manager to create a job or use T-SQL to create the job. b) You have the ability to create Database, Differential and Transaction backups using T-SQL.

Create Multiple Database Backups simultaneously SQL Server 2005 which allows you to create multiple backup copies of a database by a single TSQL statement. This feature helps us to make simultaneous backups on separate devices to increase backup reliability. Following TSQL script backup AdventureWorks database to 3 separate devices: USE master; GO BACKUP DATABASE AdventureWorks TO DISK=C:\AW1.bak Backup no. 1 MIRROR TO DISK=D:\AW2.bak Backup no. 2 MIRROR TO DISK=E:\AW3.bak Backup no. 3 WITH FORMAT; GO

How to implement your backup model? You can run backups manually,but the best approach is to schedule backups using SQL Agent. Once you set up the backup job, let SQL Agent run the backups on a set schedule. This can be done by the following ways: 1) Enterprise Manager a) Right click on the database name. b) Select "All Tasks." c) Select "Backup Database." d) Once the options are set, you can then use the schedule option to create a job. 2) T-SQL a) Using BACKUP commands, you can create the command and then use Enterprise Manager to create a job or use T-SQL to create the job. b) You have the ability to create Database, Differential and Transaction backups using T-SQL.

How to change recovery models? There are two options that can be used to switch recovery models. 1) Enterprise Manager a) Right click on the database name, select Properties, select the Options tab and select recovery model from the drop-down list. Selecting OK will change the recovery model immediately. 2) T-SQL a) ALTER DATABASE Northwind SET RECOVERY FULL b) GO

How can you rebuild the indexes? As data rows are INSERTED, UPDATED and DELETED from tables, indexes get fragmented. The greater the fragmentation, the less effective is the index. One must ensure that the fragmentation level is low or non-existent. Fragmentation level can be found by executing DBCC SHOWCONTIG statement against a particular index. There are three ways to remove fragmentation: 1. Drop and recreate the index using CREATE INDEX WITH DROP EXISTING statement 2. Execute DBCC DBREINDEX 3. Execute DBCC INDEXDEFRAG

DBCC DBREINDEX rebuilds a specified index or all indexes on the specified table. This statement allows indexes enforcing PRIMARY KEY and UNIQUE constraints to be rebuilt without dropping constraints. Using DBCC DBREINDEX is easier than coding individual DROP INDEX and CREATE INDEX statements for each index on a table. DBCC INDEXDEFRAG removes fragmentation from a specified clustered or non-clustered index.

How to debug T-SQL stored procedures? I will execute -- or step into -- a sample T-SQL stored procedure and assign values to input parameters, inspect variable contents, follow the logical flow of the procedure during runtime, evaluate T-SQL expressions, view the procedure's output, set breakpoints and generally examine the state of the environment. (Future tips will continue along this same theme.) We will debug our procedure, not from Management Studio but from the Visual Studio 2005 development environment. I mention this because under SQL Server 2000 we are able to debug stored procedures using Query Analyzer. Perhaps debugging capabilities will be added to Management Studio in the future.

How to tune Reporting Services? The following are the ways to tune Reporting Services:a) Move the Reporting service and databases to a different server if needed, or expand your current server. b) Depending on report characteristics and application logic, it is sometimes better to have a copy of data set aside for reporting purposes. This will garner better performance in both environments. For example, if your reports are for decision support or reading static historical data, you can copy the needed data on a periodic basis and set it aside. You can also use continuous replication for reporting so as not to interfere with the OLTP environment, maybe having different indexes, data structures, etc. c) If a copy of the data is not available, using a with (nolock) hint or a transaction isolation level read uncommitted (dirty read) in the reports' queries can improve performance and solve locking problems. This can be accomplished only if the database design and application logic permit dirty reads.

How to Upgrade stored procedures in SQL Server 2005? CREATE PROCEDURE my_procedure {other parameters go here}, @optionalparameter Boolean=FALSE AS If @optionalparameter=TRUE Begin {NEW version of stored procedure with SQL Server 2005-specific commands goes here} End Else Begin {OLD version of stored procedure goes here} End Existing front-end calls to the stored procedure will not use the optional parameter and will execute old code. You can test the stored procedure in place using new front-end code and then gracefully upgrade existing references to the stored procedure as you go. Since the parameter is optional all the existing calls to the stored procedure (i.e., those without the parameter) will go

through exactly as before.

How do you restore the database in SQL Server 2005? To restore the database we may need to use the MOVE option to move the physical files to a different location and also the NORECOVERY option if we want to restore multiple backup files (i.e. full, differential and logs). In our output above the data files were located in the C: \Program Files\Microsoft SQL Server\MSSQL$TEST\data directory, but we now need to restore to the D: and E: drive on a different server. The command would look like this. RESTORE DATABASE NORTH FROM DISK = 'C:\SQL\Backup\North.bak' WITH MOVE 'NORTH_Data' TO 'D:\SQL\Data\North_Data.mdf', MOVE 'NORTH_Log' TO 'E:\SQL\Log\North_Log.ldf'

How to restore the database with full, differential and log files? Following is the command used to restore and move both a full, differential and log backups:RESTORE DATABASE NORTH FROM DISK = 'C:\SQL\Backup\North.bak' WITH NORECOVERY, MOVE 'NORTH_Data' TO 'D:\SQL\Data\North_Data.mdf', MOVE 'NORTH_Log' TO 'E:\SQL\Log\North_Log.ldf' RESTORE DATABASE NORTH FROM DISK = 'C:\SQL\Backup\North_Diff.bak' WITH NORECOVERY, MOVE 'NORTH_Data' TO 'D:\SQL\Data\North_Data.mdf', MOVE 'NORTH_Log' TO 'E:\SQL\Log\North_Log.ldf' RESTORE LOG NORTH FROM DISK = 'C:\SQL\Backup\North_Log.bak' WITH RECOVERY, MOVE 'NORTH_Data' TO 'D:\SQL\Data\North_Data.mdf', MOVE 'NORTH_Log' TO 'E:\SQL\Log\North_Log.ldf' Please check and let me know if any modifications are required.

How to report on space utilization in data and log files?

You can expand or shrink a data file or a transaction log file, possibly when using the DBCC SHRINKDATABASE or DBCC SHRINKFILE command. The sysindexes table can become inaccurate over time, especially in databases that grow frequently and/or shrink frequently. The DBCC UPDATEUSAGE command reports and corrects inaccuracies in the sysindexes table. You should execute this statement if you expect your database or table size to

be different than what is reported by sp_spaceused system procedure. You must execute DBCC UPDATEUSAGE after each time you shrink database files with DBCC SHRINKDATABASE or DBCC SHRINKFILE, or as a regularly scheduled maintenance task.

Rewrite complex subqueries with temporary tables Oracle created the global temporary table (GTT) and the SQL WITH operator to help divide-andconquer complex SQL sub-queries (especially those with WHERE clause subqueries, SELECT clause scalar subqueries and FROM clause in-line views). Tuning SQL with temporary tables (and materializations in the WITH clause) can result in amazing performance improvements.

Use minus instead of EXISTS subqueries Some say that using the minus operator instead of NOT IN and NOT Exists will result in a faster execution plan.

Use SQL analytic functions The Oracle analytic functions can do multiple aggregations (e.g. rollup by cube) with a single pass through the tables, making them very fast for reporting SQL.

Re-write NOT EXISTS and NOT EXISTS subqueries as outer joins In many cases of NOT queries (but ONLY where a column is defined as NULL), you can re-write the uncorrelated subqueries into outer joins with IS NULL tests. Note that this is a non-correlated subquery, but it could be re-written as an outer join. select book_key from book where book_key NOT IN (select book_key from sales); Below we combine the outer join with a NULL test in the WHERE clause without using a sub-query, giving a faster execution plan. select b.book_key from book b, sales s where b.book_key = s.book_key(+) and s.book_key IS NULL;

Index your NULL values If you have SQL that frequently tests for NULL, consider creating an index on NULL values. To get around the optimization of SQL queries that choose NULL column values (i.e. where emp_name IS NULL), we can create a function-based index using the null value built-in SQL function to index only on the NULL columns.

Leave column names alone Never do a calculation on an indexed column unless you have a matching function-based index (a.k.a. FBI). Better yet, re-design the schema so that common where clause predicates do not need transformation with a BIF: where salary*5 > :myvalue where substr(ssn,7,4) = "1234"

C - A "Programming language" OR an "Intermediate language"! C has facilities for structured programming and allows lexical variable scope and recursion. Parameters of C functions are always passed by value. Pass-by-reference is achieved in C by explicitly passing pointer values. C program source text is free-format, using semicolon as a statement terminator (not a delimiter). A simple program in C as follows:#include <stdio.h> int main(void) { printf("hello, world\n"); return 0; } C is used as an intermediate language by some higher-level languages. This is implemented in one of two ways, as languages which: 1. Emit C source code, and one or more other representations: machine code, object code, and/or byte codes. Examples: some dialects of Lisp (Lush, Gambit), Squeaks C-subset Slang. 2. Emit C source code only, and no other representation. Examples: Eiffel, Sather, Esterel, and Vala. C source code is then input to a C compiler, which then outputs finished machine or object code. This is done to gain portability (C compilers exist for nearly all platforms) and to avoid having to develop machine-specific code generators.

The dimension of character string is always defined to be larger than maximum number of characters required to store in the array. When a character string is declared,the last element in a character array is reserved,by convention,to store the string terminator character \0.So,the dimension of character string is always defined to be larger than maximum number of characters required to store in the array,so as to take care of string terminator.

Conditional Compilation in C! In C, compiler can skip over a part of a source code by inserting the preprocessing commands #ifdef and #endif which have general form as: #ifdef macroname statement1; statement2; statement3; #endif If a macroname has been defined #ifdef then it will not get processed. Now, when we need to compile only a part of program. There are two cases: 1.It often happens that a program is need to be changed at the last minute, to satisfy a client. This involves rewriting some part of source code to the clients satisfaction and delete the old code. But then it may happen that this code can be required by some other application. In such case, we can write this code in between #ifdef and #endif directives, and remove them whenever the code required.

Вам также может понравиться