C for dummies pdf download






















Two billion is a very large number: plenty big enough for most uses. In fact, your computer probably executes faster than 2 gigahertz, depending upon how old your computer is. Giga is the prefix meaning billion. An unsigned int value type can represent a number from 0 to 4,,,, should the need arise for some unimaginable reason. You can declare a variable simply unsigned. The int is implied. Solving the truncation problem The limitations of int variables can be unacceptable in some applications.

A decimal number can have a nonzero fractional part. Mathematicians also call those real numbers. Decimal numbers avoid many of the limitations of int type integers. The equivalent integer is written simply as 1. Decimals numbers can also be negative, like —2. Floatingpoint variables are declared in the same way as int variables: double dValue1; From this point forward, the variable dValue1 is declared to be a double.

Once declared, you cannot change the type of a variable. This is not necessarily the case. Looking at the limits of floating-point numbers Although floating-point variables can solve many calculation problems such as truncation, they have some limitations themselves — in effect, the reverse of those associated with integer variables.

But what about 0. Should these also be considered as 1? Calculation speed Historically, a computer processor can process integer arithmetic quicker than it can floating-point arithmetic. Calculation speed is becoming less of a problem as microprocessors increase their capabilities.

Loss of accuracy Floating-point variables cannot solve all computational problems. Floatingpoint variables have a limited precision of about 6 digits — an extra-economy size, double-strength version of float can handle some 15 significant digits with room left over for lunch. To evaluate the problem, consider that 13 is expressed as 0. The concept of an infinite series makes sense in math, but not to a computer. The computer has a finite accuracy. Average 1, 2, and 2 for example , and you get 1.

The maximum value of a double variable is roughly 10 to the 38th power. Only the first 13 digits or so have any meaning; the remaining 25 digits suffer from floating-point round-off error. Chapter 2: Declaring Variables Constantly Declaring Variable Types So far this chapter has been trumpeting that variables must be declared and that they must be assigned a type.

Fortunately ta-dah! This smaller version takes less memory than a double but has less accuracy and a smaller range. Not suitable for arithmetic. Logically false. In days gone by, memory was an expensive asset — you could reap significant space savings by using a float variable. This is no longer the case. That, combined with the fact that modern processors perform double precision calculations at the same speed as float, makes the double the default. Bigger is better, after all.

Types of constants A constant is an explicit number or character such as 1, 0. As with variables, every constant has a type. The analogy is as follows: 1 represents a single ball in the bed of a pickup truck, whereas 1L is a single ball in the bed of a dump truck. The ball is the same, but the capacity of its container is much larger.

Following the int to long comparison, 1. Notice, however, that the default for floating-point constants is double. Thus, 1. You can also store a set of non-printable characters that is used as character constants. See Table for a description of these important nonprintable characters. The type bool comes from Boolean, the last name of the inventor of the logical calculus. There are two values for a boolean variable: true and false.

There are actually calculations that result in the value bool. That is, you are allowed to add an integer with a double precision floating-point value. Mixed-mode expressions generate a value whose type is equal to the more capable of the two operands. Converting a larger value type into a smaller value type is called demotion, whereas converting values in the opposite direction is known as promotion.

You can immediately recognize dVariable as a variable of type double by using this convention. Character Type n int l long f float d double c character sz string These leading characters help the programmer keep track of the variable type. Mixed-mode expressions are not a good idea. Programs have to be able to perform these operations in order to get anything done. If you can say var1 op var2, op must be a binary operator.

The most common binary operators are the simple operations you performed in grade school. The binary operators are flagged in Table You may not have encountered modulus in your studies. For example, 4 goes into 15 three times with a remainder of 3. I discuss round-off errors in Chapter 2. Every expression has a type such as int, double, char, and so on. A statement involving any mathematical operator is an expression since all these operators return a value. Remember that constants without decimal points are ints.

Expressions can be complex or extremely simple. In fact, the statement 1 is an expression because it has a value 1 and a type int. Determining the Order of Operations All operators perform some defined function. In addition, every operator has a precedence — a specified place in the order in which the expressions are evaluated. The precedence of the operators determines who goes first. Table shows that multiplication has higher precedence than addition, so the result is 7. The concept of precedence is also present in arithmetic.

So what happens when we use two operators of the same precedence in the same expression? When operators of the same precedence appear in the same expression, they are evaluated from left to right the same rule applied in arithmetic.

Thus, the answer is 8 divided by 4, which is 2 divided by 2 which is 1. But what if the programmer wanted to divide x by plus 32? The programmer can change the precedence by bundling expressions together in parentheses shades of algebra! Multiplication and division have higher precedence than addition and subtraction. C remains one of the most in-demand programming language skills. If you have a basic understanding of coding and need to learn C —or need a reference on the language in order to launch or further your career—look no further.

This site comply with DMCA digital copyright. We do not store files not owned by us, or without the permission of the owner. For example, the function strncat target, source, count tacks the second string source onto the end of the first argument target.

An example output from the program appears as follows: Enter string 1:Chester Enter string 2:Dog Chester - Dog Press any key to continue. The program begins by reading a string from the keyboard. Characters up to the first whitespace are read, the whitespace character is tossed, and www. This causes a dangerous overflow condition that hackers can and will exploit to put a virus in your program. For example, the function getline inputs a line of text; however, this function accepts the length of the string as one of its arguments: cin.

The strncpy and strncat functions accept the length of the target buffer as one of their arguments. I use the term string to refer to an array of characters terminated by a null and string type to refer to the type string. The string type based StringConcatenate program appears as follows: www. The StringConcatenate program manipulates the string type variables as it would any other.

Notice that some operations have to be understood in a slightly different way from their arithmetic equivalent. Operations on string type variables are defined in the string include file. The string class is discussed further in Chapter This chapter introduces the pointer variable type. Memory is measured in bytes or bits. For example, you may find that an int is smaller than a long.

The sizes output by the VariableSize program are typical for a bit processor such as the Pentium class processors. A variable intReader might be at address 0x, whereas floatReader might be over at location 0x By convention, memory addresses are expressed in hexadecimal. Of course, intReader and floatReader might www. This is somewhat analogous to a hotel. When you make your reservation, you may be assigned room 0x I know that suite numbers are normally not expressed in hexadecimal, but bear with me.

Your buddy may be assigned 80 doors down in room 0x Each variable is assigned an address when it is created more on that later in this chapter when we talk about scope. Address Operators The two pointer-related operators are shown in Table Your results may vary.

The absolute address of program variables depends on a lot of factors. Notice how the variable n is exactly 4 bytes from the first variable declared m2. The variable l appears 4 bytes down from that. The double variable d is a full 8 bytes from its neighboring variable f. Using Pointer Variables A pointer variable is a variable that contains an address, usually the address of another variable.

Returning to my hotel analogy for a moment, I might tell my son that I will be in room 0x on my trip. My son is a pointer variable of sorts. The next statement declares the variable pintVar to be a variable of type pointer to an int. By the way, pintVar is pronounced pee-int-Var, not pint-Var. Thus, they would say splat pintVar. Many programmers adopt a naming convention in which the first character of the variable name indicates the type of the variable, such as n for int, d for double, and so on.

A further aspect of this naming convention is to place a p at the beginning of a pointer variable name. Thus, we would read the first assignment as store the address of intVar in pintVar.

To make this more concrete, assume that the memory for function fn starts at location 0x In addition, assume that intVar is at address 0x and that pintVar is at 0x The layout here is simpler than the actual results from the Layout program; however, the concepts are identical. Your house has a unique address. Each byte in memory has an address that is unique. A house address is made up of both numbers and letters. For example, my address is Main Street. You can store a couch in the house at Main Street — you can store a number in the byte located at 0x You can now store a couch at the house with the address written on the piece of paper.

Assign the address of myHouse to the House pointer, houseAddress. Now store a couch at the house located at the address stored in houseAddress. Assign the address of myInt to the pointer intAddress. Finally, assign 10 to the int that intAddress points to. Using different types of pointers Every expression has a type as well as a value. This is equivalent to saying that, if houseAddress is the address of a house, the thing pointed at by houseAddress must be a house. Amazing, but true.

That is, an address on a Pentium is 4 bytes long, period. Matching pointer types is extremely important.

Save a variable into an area of the wrong size, and nearby variables can be wiped out. This is demonstrated graphically in the following LayoutError program. The assumption made here is that these three variables are laid out next to each other. The next three executable lines output the value of the three variables. Not surprisingly, all three variables display as 0. After assigning the double value The variable hotelAddress is a pointer to a hotel.

Now, the house address is cast into the address of a hotel and saved off into the variable hotelAddress. Finally, TheRitz is plopped down on top of my house. The type of pointer saves the programmer from stuffing an object into a space that is too big or too small. Passing Pointers to Functions One of the uses of pointer variables is in passing arguments to functions. To understand why this is important, you need to understand how arguments are passed to a function.

Passing by value You may have noticed that it is not normally possible to change the value of a variable passed to a function from within the function. Consider the following example code segment: www. The value of n1 is then passed to fn. Upon entering the function, intArg is equal to 10, the value passed. Perhaps surprisingly, upon returning to parent , the value of n1 is still 0.

That is, the expression is evaluated, even if it is just a variable name, and the result is passed. The significance of this difference is apparent when you consider the assignment within fn.

Upon returning to parent , the value of n is 10 because n is just another name for 0x In the following example, the variable n is passed by reference. The fn function stores the value 10 into int location referenced by intArg. Notice that reference is not an actual type. Making Use of a Block of Memory Called the Heap The heap is an amorphous block of memory that your program can access as necessary.

This section describes why it exists and how to use it. Managed programs rely upon the. NET framework. This book only covers unmanaged mode programming. In order to understand the dangers, you must know something about variable scope.

Besides being a mouthwash, scope is the range over which a variable is defined. The function main immediately invokes parent. At that point, intParent goes into scope — that is, intParent is defined and available for the remainder of the function parent. The second statement in parent is the call to child. Once again, the function child declares a local variable, this time intChild.

The variable intChild is within the scope of child. When child exits, the variable intChild goes out of scope. Not only is intChild no longer accessible, but it no longer even exists. The memory occupied by intChild is returned to the general pool to be used for other things. As parent continues executing, the variable intLater goes into scope at the declaration. At the point that parent returns to main , both intParent and intLater go out of scope.

The programmer may declare a variable outside of any function. This type of variable, known as a global variable, remains in scope for the duration of the program. Because intGlobal is declared globally in this example, it is available to all three functions and remains available for the life of the program. Thus, by the time the memory address www. This error is very common because it can creep up in a number of different ways.

Unfortunately, this error does not cause the program to instantly stop. In fact, the program may work fine most of the time — that is, the program continues to work as long as the memory formerly occupied by dLocalVariable is not reused immediately.

Such intermittent problems are the most difficult ones to solve. What is needed is a block of memory controlled by the programmer. Such a block of memory is called the heap. Heap memory is allocated using the new command followed by the type of object to allocate. For example, the following allocates a double variable off the heap.

After the function is finished with the memory location, it is returned to the heap. The function parent sets the pointer to zero after the heap memory has been returned — this is not a requirement, but a very good idea. A program that crashes immediately upon encountering an error is much easier to fix than one that is intermittent in its behavior.

NET—managed mode. NET programs. The concept of pointer variables is introduced in Chapter 8. Defining Operations on Pointer Variables Some of the same operators I cover in Chapter 3 can be applied to pointer types. This section examines the implications of applying these operators to both to pointers and to the array types I discuss arrays in Chapter 7. Table lists the three fundamental operations that are defined on pointers.

The real estate memory model which I use so effectively in Chapter 8, if I do say so myself is useful to explain how pointer arithmetic works. Consider a city block in which all houses are numbered sequentially. Extending this concept one step further, it makes no sense to add Main Street to Main Street. Re-examining arrays in light of pointer variables Now return to the wonderful array for just a moment. An array is just like my city block. Each element of the array corresponds to a house on that block.

Say that the house right on the corner is Main Street, which means that the house one house from the corner is Main Street, and so on. Take that same model back to the world of computer memory. Consider the case of an array of 32 1-byte characters called charArray. If the first byte of this array is stored at address 0x, the array will extend over the range 0x through 0x12f.

Take this model one step further to the world of pointer variables. The addition of an integer offset to a pointer is defined such that the relationships shown in Table are true.

Table also demonstrates why adding an offset n to ptr calculates the address of the nth element in charArray. That is, the name of an array without a subscript present is the address of the array itself. The function then loops through each element of the array. On each loop, displayArray outputs the current integer that is, the integer pointed at by pArray before incrementing the pointer to the next entry in intArray. The use of pointers to access arrays is nowhere more common than in the accessing of character arrays.

Expanding pointer operations to a string A null terminated string is simply a character array whose last character is a null. This null terminated array serves as a quasi-variable type of its own. See Chapter 7 for an explanation of string arrays. The following code examples compare this technique to the earlier technique of indexing in the array.

Character pointers enjoy the same relationship with a character array that any other pointer and array share. The for loop chosen stops when the index reaches 5, the length of the string. The second loop displays the same string using a pointer. The program sets the variable pszString equal to the address of the first character in the array. It then enters a loop that will continue until the char pointed at by pszString is equal to false — in other words, until the character is a null.

The integer value 0 is interpreted as false — all other values are true. The answer is partially pre- historic and partially human nature. These compilers could not perform the complicated optimizations that modern compilers can. In the old days of C, saving a few computer instructions was a big deal.

This gave C a big advantage over other languages of the day, notably Fortran, which did not offer pointer arithmetic. After all, a char occupies a single byte. If szTarget is stored at 0x, the sixth element is located at 0x Once again, the dusty old house analogy works here as well. I mean dusty analogy, not dusty house. Contrasting a pointer with an array There are some differences between indexing into an array and using a pointer.

This problem is not generally a problem of the processor or the operating system but of the application. A second difference between a pointer and the address of an array is the fact that charArray is a constant, whereas pArray is not. Arrays of pointers are a type of array of particular interest.

Just as arrays may contain other data types, an array may contain pointers. The following declares an array of pointers to ints: www. The following two examples show why arrays of character strings are useful. Utilizing arrays of character strings Suppose I need a function that returns the name of the month corresponding to an integer argument passed to it. The month 0 is assumed to be invalid as are any numbers greater than A more elegant solution uses the integer value for the month as an index into an array of pointers to the names of the months.

If nMonth is valid, the function uses it as an offset into an array containing the names of the months. This technique of referring to character strings by index is especially useful when writing your program to work in different languages. For example, a program may declare a ptrMonths of pointers to Julian months in different languages.

The program would initialize ptrMonth to the proper names, be they in English, French or German for example at execution time. These strings contain the arguments to the program. These arguments are also known as parameters. There is an exact Windows analog that will appear here in just a second. The first argument is an int that I have been calling quite descriptively, as it turns out nNumberofArgs. The first argument is the name of the program. Thus, pszArgs[0] points to PrintArgs. The remaining elements in pszArgs point to the program arguments.

The element pszArgs[1] points to arg1, and pszArgs[2] to arg2, for example. Select Parameters under the Debug menu. The program output appears as it would from the DOS prompt.

Accessing program arguments Windows-style Windows passes arguments as a means of communicating with your program as well. Try the following experiment. Find the executable file using Windows Explorer. Select multiple file names by clicking several files while pressing the Ctrl key or by using the Shift key to select a group.

The name of each file appears as output. Notice that the name of each file appears as a single argument, even though the file name may include spaces. Also note that Windows passes the full pathname of the file. Using the drag-and-drop feature is an easy way to pass arguments to your program at startup. That leaves you with two alternatives: You can give up on programming now while you still have a chance, or you can find and fix your errors. In this chapter, you find out how to track down and eradicate software bugs.

Compile-time errors are relatively easy to fix because the compiler generally points you to the problem. These are known as run-time errors. You can use two different techniques for finding bugs. You can add output statements at key points.

A second approach is to use a separate program called a debugger. I cover both of these debugging techniques in this chapter. Unfortunately, the program contains two errors, one that makes the program crash and one that causes the program to generate incorrect results. The following steps route out the problem. I enter my trusty 1, 2, and 3 followed by —1, but get quite a shock when the nasty message shown in Figure appears instead of the expected average.

Figure The initial version of Error Program terminates suddenly instead of generating the expected output. Fortunately, the first line of the error message is descriptive of the problem. The message also spits out the memory address where the division occurred, but this is of little use because you have no idea where in the program that address may be. That happens a lot more often than you might think. The CPU may just happen to execute a divide instruction with a denominator of zero, thereby generating a divide by zero error message and masking the source of the problem.

I feel reasonably certain that at the time of the division, nNums must have been equal to zero. Clearly nNums should have been incremented during each loop of the input section. The output shown here includes a ridiculous value for average: This program generates incorrect results Enter another number:1 Enter another number:2 Enter another number:3 Enter another number Average is: Press any key to continue To get any farther, you need to know the value of these variables.

In fact, it would help to know the value of nValue as well because nValue is used to calculate nSum. The result of executing the program with the now standard 1, 2, 3, and —1 input is shown next.

Even on the first loop, the value of nSum is unreasonable. In fact, at this point during the first loop, the program has yet to add a new value to nSum. You would think that the value of nSum should be 0. This time you see the expected average value of 2. Adding output statements is simple enough, and the programs rebuild quickly so the cycle time is short enough.

Further, in order to change an output statement, the programmer must rebuild the entire program. For a large program, this rebuild time can be significant.

I have worked on programs that took most of the night to rebuild. A pointer written to the display in hex means nothing, and as soon as you attempt to dereference the pointer, the program blows. A second, more sophisticated technique is based on a separate utility known as a debugger. However, this approach involves learning to use a debugger. The programmer controls the debugger through commands by means of the same interface as the editor.

You can access these commands in menu items or by using hot keys. She can execute one step at a time in the program, she can stop the program at any point, and she can examine the value of variables.

Fortunately, most debuggers offer the same basic commands. Table lists the command hot keys you use in both environments. Running a test program The best way to learn how to fix a program using the debugger is to go through the steps to fix a buggy program.

The following program has several problems that need to be discovered and fixed. Execute the program. Single-stepping through a program The best first step when tracking down a program problem is to execute the program in debugger mode.

Sometimes, the debugger can give you more information about the problem. Click OK to acknowledge the error and then the Program Reset from the Debug menu or the Stop Execution command from the Debug toolbar to make sure that everything within the debugger is reset back to the beginning. To see exactly where the problem occurs, execute just a part of the program.

The debugger lets you do this through what is known as a breakpoint. The debugger stops the program if execution ever passes through a breakpoint. The debugger then gives control back to the programmer. Now set a breakpoint at the first executable statement by clicking in the trough just to the left of the reference to cout immediately after main or pressing F5 as shown in Table A small red circle with a check appears.

The display now appears like the one shown in Figure Now execute the program under the debugger again, either by selecting the Debug item under the Debug menu, by clicking the blue check mark on the debug toolbar, or by pressing F8. Program execution starts like normal but immediately stops on the first line. The line containing the breakpoint turns from red to blue, indicating that execution has halted at that point.

Figure A breakpoint shows up as a small red circle with a check. The blue marking moves to the next executable statement, skipping over both declarations. A declaration is not a command and is not executed. You can switch to the Console window to see that the single output statement has executed, as shown in Figure Figure You can click the Console window at any time to see any program output. So far, so good. When you select Next Step one more time, however, the program crashes ignominiously just as before.

You now know that the problem is encountered somewhere within the StringEmUp function. When the program crashes within a function, either the function contains a bug, or the arguments passed to the function are incorrect.

The Next Step command treats a function call like a single command. Starting from the most basic level is significant in achieving a greater level of success. So as hacking is prevalent and common nowadays, so everyone should have knowledge about it.

Even though hacking pertains to a vast area of knowledge and issues, the major topics which will be presented in a detailed and elaborate way include the following: A preliminary account of hacking, as a regime of information technology knowledge and its connections and areas of concern which need to be discussed and explored.

The basic activities which hackers perform. A step-by-step discussion of activities which are followed by hackers during any hacking venture. An account of the hacking practices which enable the attack over emails and the Windows operating system. The different types of hacking attacks which can target web servers. Introduction to C ProgrammingThis textbook was written with two primary objectives. The first is to introduce the C program-ming language. C is a practical and still-current software tool; it remains one of the most popular programming languages in existence, particularly in areas such as embedded systems.

C facilitates writing code that is very efficient and powerful and, given the ubiquity of C compilers, can be easily ported to many different platforms. Also, there is an enormous code-base of C programs developed over the last 30 years, and many systems that will need to be maintained and extended for manyyears to come. The second key objective is to introduce the basic concepts of software design.

At one-level thisis C-specific: to learn to design, code and debug complete C programs. At another level, it is moregeneral: to learn the necessary skills to design large and complex software systems. This involves learning to decompose large problems into manageable systems of modules; to use modularity andclean interfaces to design for correctness, clarity and flexibility.



0コメント

  • 1000 / 1000