1 What is a Pointer A pointer is



















![argv[0] - "myecho" argv[1] - "aaa" argv[2] - "bbb" argv[3] - "ccc" 19. What argv[0] - "myecho" argv[1] - "aaa" argv[2] - "bbb" argv[3] - "ccc" 19. What](https://slidetodoc.com/presentation_image_h/030dd9c0159e8eb1342d139b23a0fb54/image-20.jpg)





























- Slides: 49
1. What is a Pointer? A pointer is a variable which contains the address in memory of another variable. We can have a pointer to any variable type. The unary or monadic operator & gives the ``address of a variable''. The indirection or dereference operator * gives the ``contents of an object pointed to by a pointer''. To declare a pointer to a variable do: int *pointer; NOTE: We must associate a pointer to a particular type: You can't assign the address of a short int to a long int, for instance. Consider the effect of the following code: int x = 1, y = 2; int *ip;
ip = &x; y = *ip; x = ip; *ip = 3; It is worth considering what is going on at the machine level in memory to fully understand how pointer work. Consider Fig. 9. 1. Assume for the sake of this discussion that variable x resides at memory location 100, y at 200 and ip at 1000. Note A pointer is a variable and thus its values need to be stored somewhere. It is the nature of the pointers value that is new.
Fig. 9. 1 Pointer, Variables and Memory Now the assignments x = 1 and y = 2 obviously load these values into the variables. ip is declared to be a pointer to an integer and is assigned to the address of x (&x). So ip gets loaded with the value 100. Next y gets assigned to the contents of ip. In this example ip currently points to memory location 100 -- the location of x. So y gets assigned to the values of x -- which is 1. We have already seen that C is not too fussy about assigning values of different type. Thus it is perfectly legal (although not all that common) to assign the current value of ip to x. The value of ip at this instant is 100. Finally we can assign a value to the contents of a pointer (*ip). IMPORTANT: When a pointer is declared it does not point anywhere. You must set it to point somewhere before you use it. So. . . int *ip; *ip = 100; will generate an error (program crash!!). The correct use is: int *ip;
int x; ip = &x; *ip = 100; We can do integer arithmetic on a pointer: float *flp, *flq; *flp = *flp + 10; ++*flp; (*flp)++; flq = flp; NOTE: A pointer to any variable type is an address in memory -- which is an integer address. A pointer is definitely NOT an integer. The reason we associate a pointer to a data type is so that it knows how many bytes the data is stored in. When we increment a pointer we increase the pointer by one ``block'' memory.
So for a character pointer ++ch_ptr adds 1 byte to the address. For an integer or float ++ip or ++flp adds 4 bytes to the address. Consider a float variable (fl) and a pointer to a float (flp) as shown in Fig. 9. 2 Pointer Arithmetic Assume that flp points to fl then if we increment the pointer ( ++flp) it moves to the position shown 4 bytes on. If on the other hand we added 2 to the pointer then it moves 2 float positions i. e 8 bytes as shown in the Figure. 2. List out all the conditional statements available in C. If , If – else if statement, switch, while, do-while, for statement. 3. List out all the unconditional statements available in C. Break, continue, goto.
4. What are the different storage classes available in C? Auto, extern, register, static. 5. Which storage class is the default for the variables? Auto for local variables, static for global variables. 6. What is a self referential structure? A self-referential structure is a data structure that includes references to other data of its same type. A simple example of this would be an implementation in C of a linked list: typedef struct listnode { void *data; struct listnode *next; } list_t; The reference to a listnode struct from within a listnode struct is the selfreferential aspect of the structure.
7. What are the different iterative statements available in C? While , do-while, for. 8. Differentiate structure from union? (a) In union , the different members share the same memory location. The total memory allocated to the union is equal to the maximum size of the member. Union can hold data of only one member at a time. (b) In structure, the different members have different memory location. The total memory allocated to the structure is equal to the sum of memory allocated for each member. Structure can hold data of more than one member at a time.
10. What is preprocessor? The C preprocessor (cpp) is the preprocessor for the C programming language. In many C implementations, it is a separate program invoked by the compiler as the first part of translation. The preprocessor handles directives for source file inclusion (#include), macro definitions (#define), and conditional inclusion (#if). The language of preprocessor directives is not strictly specific to the grammar of C, so the C preprocessor can also be used independently to process other types of files. The transformations it makes on its input form the first four of C's so-called Phases of Translation. Though an implementation may choose to perform some or all phases simultaneously, it must behave as if it performed them one-by-one in order. Examples This section goes into some detail about C preprocessor usage. Good programming practice when writing C macros is crucial, particularly in a collaborative setting, so notes on this have been included. Of course, it is possible to abuse these features, but this is not recommended in a production environment.
Including files The most common use of the preprocessor is to include another file: #include <stdio. h> int main (void) { printf("Hello, world!n"); return 0; } The preprocessor replaces the line #include <stdio. h> with the system header file of that name, which declares the printf() function amongst other things. More precisely, the entire text of the file 'stdio. h' replaces the #include directive. This can also be written using double quotes, e. g. #include "stdio. h". The angle brackets were originally used to indicate 'system' include files, and double quotes user-written include files, and it is good practice to retain this distinction. C compilers and programming environments all have a facility which allows the programmer to define where include files can be found. This can be introduced through a command line flag, which can be parameterized using a makefile, so that a different set of include files can be swapped in for different operating systems, for instance.
By convention, include files are given a. h extension, and files not included by others are given a. c extension. However, there is no requirement that this be observed. Occasionally you will see files with other extensions included, in particular files with a. def extension may denote files designed to be included multiple times, each time expanding the same repetitive content. #include often compels the use of #include guards or #pragma once to prevent double inclusion. Conditional compilation The #ifdef, #ifndef, #else, #elif and #endif directives can be used for conditional compilation. #define __WINDOWS__ #ifdef __WINDOWS__ #include <windows. h> #else #include <unistd. h> #endif
The first line defines a macro __WINDOWS__. The macro could be defined implicitly by the compiler, or specified on the compiler's command line, perhaps to control compilation of the program from a make file. The subsequent code tests if a macro __WINDOWS__ is defined. If it is, as in this example, the file <windows. h> is included, otherwise <unistd. h>. Since the preprocessor can also be invoked independently to process files apart from compiling source code, it can also be used as a "general purpose preprocessor" for other types of text processing (see General purpose preprocessor for examples). Macro definition and expansion There are two types of macros, object-like and function-like. Function-like macros take parameters; object-like macros don't. The generic syntax for declaring an identifier as a macro of each type is, respectively, #define <identifier> <replacement token list> #define <identifier>(<parameter list>) <replacement token list> Note that there must not be any whitespace between the macro identifier and the left parenthesis.
Wherever the identifier appears in the source code it is replaced with the replacement token list, which can be empty. For an identifier declared to be a function-like macro, it is only replaced when the following token is also a left parenthesis that begins the argument list of the macro invocation. The exact procedure followed for expansion of function-like macros with arguments is subtle. Object-like macros are conventionally used as part of good programming practice to create symbolic names for constants, e. g. #define PI 3. 14159 instead of hard-coding those numbers throughout one's code. An example of a function-like macro is: #define RADTODEG(x) ((x) * 57. 29578) This defines a radians to degrees conversion which can be written subsequently, e. g. RADTODEG(34). This is expanded in-place, so the caller does not need to litter copies of the multiplication constant all over his code. The macro here is written as all uppercase to emphasize that it is a macro, not a compiled function.
Multiple evaluation of side effects Another example of a function-like macro is: #define MIN(a, b) ((a)>(b)? (b): (a)) This illustrates one of the dangers of using function-like macros. One of the arguments, a or b, will be evaluated twice when this "function" is called. So, if the expression MIN(++firstnum, secondnum) is evaluated, then firstnum may be incremented twice, not once as would be expected. A safer way to achieve the same would be to use a typeof-construct: #define max(a, b) ({ typeof (a) _a = (a); typeof (b) _b = (b); _a > _b ? _a : _b; }) This will cause the arguments to be evaluated only once, and it won't be type-specific anymore. This construct is not legal ANSI C; both the typeof keyword, and the construct of placing a compound statement within parentheses, are non-standard extensions implemented in the popular gnu C compiler (gcc). If you are using gcc, the same general problem can also be solved using a static inline function, which is as efficient as a #define. The inline function allows the compiler to check/coerce parameter types -- in this particular example this appears to be a disadvantage, since the 'max' function as shown works equally well with different parameter types, but in general having the type coercion is often an advantage. Within ANSI C, there's no reliable general solution to the issue of side-effects in macro arguments.
Semicolons One stylistic note about the above macro is that the semicolon on the last line of the macro definition is omitted so that the macro looks 'natural' when written. It could be included in the macro definition, but then there would be lines in the code without semicolons at the end which would throw off the casual reader. Worse, the user could be tempted to include semicolons anyway; in most cases this would be harmless (an extra semicolon denotes an empty statement) but it would cause errors in control flow blocks: #define PRETTY_PRINT(s) printf ("Message: "%s"n", s); if (n < 10) PRETTY_PRINT("n is less than 10"); else PRETTY_PRINT("n is at least 10"); This expands to give two statements – the intended printf and an empty statement – in each branch of the if/else construct, which will cause the compiler to give an error message similar to: error: expected expression before ‘else’
12. How many bytes, different data types require on a typical computer system? Type Length Range unsigned char 8 bits 0 to 255 char 8 bits -128 to 127 enum 16 bits -32, 768 to 32, 767 unsigned int 16 bits 0 to 65, 535 short int 16 bits -32, 768 to 32, 767 int 16 bits -32, 768 to 32, 767 unsigned long 32 bits 0 to 4, 294, 967, 295 long 32 bits -2, 147, 483, 648 to 2, 147, 483, 647 float 32 bits 3. 4 * (10**-38) to 3. 4 * (10**+38) double 64 bits 1. 7 * (10**-308) to 1. 7 * (10**+308) long double 80 bits 3. 4 * (10**-4932) to 1. 1 * (10**+4932) 13. What is a flow chart? A flowchart (also spelled flow-chart and flow chart) is a schematic representation of an algorithm or a process flowchart is one of the seven basic tools of quality control, which include the histogram, Pareto chart, check sheet, control chart, cause-and-effect diagram, flowchart, and scatter diagram.
14. What is an algorithm? An algorithm (pronounced AL-go-rith-um) is a procedure or formula for solving a problem. The word derives from the name of the mathematician, Mohammed ibn-Musa al-Khwarizmi, who was part of the royal court in Baghdad and who lived from about 780 to 850. Al-Khwarizmi's work is the likely source for the word algebra as well. A computer program can be viewed as an elaborate algorithm. In mathematics and computer science, an algorithm usually means a small procedure that solves a recurrent problem. 15. Differentiate while from do-while. - While and do-while loops are used when u want to repeat the execution of a certain statement or a set of statements. -Before entering into the loop, the while condition is evaluated. If it is true then only the body is executed. -Do-while executes the loop body at least once. The condition is checked after executing the loop body once. 16. What are the different types of comments available in C? 1. There are two kinds of comments. Block comments begin with `/*' and continue until the next `*/'. Block comments do not nest: /* this is /* one comment */ text outside comment
2. Line comments begin with `//' and continue to the end of the current line. Line comments do not nest either, but it does not matter, because they would end in the same place anyway. // this is // one comment text outside comment It is safe to put line comments inside block comments, or vice versa. /* block comment // contains line comment yet more comment */ outside comment // line comment /* contains block comment */ But beware of commenting out one end of a block comment with a line comment. // l. c. /* block comment begins oops! this isn't a comment anymore */ Comments are not recognized within string literals. "/* blah */" is the string constant `/* blah */', not an empty string.
17. Assume a C program consists of a set of functions. From which point its execution starts? Program execution always starts from Main(). 18. What are command line arguments? Program Execution Depending on the operating system and programming environment, a C program can be executed either by selecting an icon ifrom a graphical user interface desktop or by entering a command in a command window (DOS or UNIX command window). It is usually easier to write programs that are run by entering a command in a command window. When a command is entered in a command window, it is executed by a command-line interpreter. The operation of a command interpreter is quite complex, but as a first approximation, it interpreter breaks up a command into words separated by spaces. The first word is treated as the name of a program. The interpreter searches for the program and starts it executing with the command words passed as arguments. A C program is executed by calling its main() function. The function is called with one argument that indicates how many words are in the command another argument that is an array containing the command words.
Accessing Command-Line Arguments In order to access the command words, the main() function must have a prototype similar to the following. int main(int argc, char * argv[]) The names argc and argv are usually used for the parameters, but a programmer could use different names. The command words can be accessed as argv[0] through argv[argc - 1]. The program name is the first word on the command line, which is argv[0]. The command-line arguments are argv[1] through argv[argc - 1]. An Example - myecho. C The file myecho. C encodes a program that echoes its command-line arguments. This program is similar to the UNIX echo command. Suppose that the program is compiled to an executable program myecho and that the program is executed with the following command. myecho aaa bbb ccc When this command is executed, the command interpreter calls the main() function of the myecho program with 4 passed as the argc argument and an array of 4 strings as the argv argument. argc contains the following strings.
argv[0] - "myecho" argv[1] - "aaa" argv[2] - "bbb" argv[3] - "ccc" 19. What is structured programming? Structured programming is often (but not always) associated with a "top-down" approach to design. Structured programming languages It is possible to do structured programming in any programming language, though it is preferable to use something like a procedural programming language. Since about 1970 when structured programming began to gain popularity as a technique, most new procedural programming languages have included features to encourage structured programming (and sometimes have left out features that would make unstructured programming
easy). Some of the better known structured programming languages are Pascal, C, PL/I (programming language)|PL/I]], and Ada. 20. What is block structured programming? block-structured <language> Any programming language in which sections of source code contained within pairs of matching delimiters such as "{" and "}" (e. g. in C) or "begin" and "end" (e. g. Algol) are executed as a single unit. A block of code may be the body of a subroutine or function, or it may be controlled by conditional execution (if statement) or repeated execution (while statement, for statement, etc. ). In all but the most primitive block structured languages a variable's scope can be limited to the block in which it is declared. Block-structured languages support structured programming where each block can be written without detailed knowledge of the inner workings of other blocks, thus allowing a top-down design approach. top-down design <programming> (Or "stepwise refinement"). The software design technique which aims to describe functionality at a very high level, then partition it repeatedly into more detailed levels one level at a time until the detail is sufficient to allow coding. This approach to software design probably originated at IBM, and grew out of structured programming practices.
21. What is a local variable? Local variables must always be defined at the top of a block. When a local variable is defined - it is not initalised by the system, you must initalise it yourself. A local variable is defined inside a block and is only visable from within the block. main() { int i=4; i++; } When execution of the block starts the variable is available, and when the block ends the variable 'dies'. A local variable is visible within nested blocks unless a variable with the same name is defined within the nested block.
main() { int i=4; int j=10; i++; if (j > 0) { printf("i is %dn", i); /* i defined in 'main' can be seen */ } if (j > 0) { int i=100; /* 'i' is defined and so local to * this block */ printf("i is %dn", i); } /* 'i' (value 100) dies here */ printf("i is %dn", i); /* 'i' (value 5) is now visable. */ }
22. What is a global variable? How do you declare it? Global variables ARE initialized by the system when you define them! Data Type Initialser int 0 char '