Prepared by: S. Vairamuthu & Mrs. B. Selva Rani, School of Computing Sciences, VIT

Size: px
Start display at page:

Download "Prepared by: S. Vairamuthu & Mrs. B. Selva Rani, School of Computing Sciences, VIT"

Transcription

1 Pointers Why we need pointers? The correct understanding and use of pointers is crucial to successful C programming. There are several reasons for this: First, pointers provide the means by which functions can modify their calling arguments. Second, pointers support dynamic allocation. Third, pointers can improve the efficiency of certain routines. Finally, pointers provide support for dynamic data structures, such as binary trees and linked lists. Memory addresses are global to all functions, whereas local variable names are meaningful only within the functions in which they are declared. A function can pass the address of a local variable to another function, and the second functions can use this address to access the contents of the first function s local variable. What are pointers? A pointer is a variable that holds a memory address. This address is the location of another object (typically another variable) in memory. For example, if one variable contains the address of another variable, the first variable is said to be point to the second. To make this explanation clearer, we re going to look some examples of source code, and draw pictures to show what is happening in memory. To keep things consistent, we re going to develop a pictorial notation that will be used throughout this discussion. Let s start off with an example. This is a very simple program. The diagram on the right shows what is happening in memory. The rectangular boxes indicate memory locations. The value inside a box indicates the value in that memory location. The value under a box is the memory address of that box. In this case, we have three boxes one for each of the three variables in

2 main(). The name of each variable has been identified to the left of each box. Not all boxes will have names: memory locations allocated by malloc() will be nameless. Finally, all of these boxes represent local variables within the function main(). We have represented this with a rounded rectangle. Look first at Diagram 2a. This shows the state of the program memory just after line 5 has been executed. The variable num was assigned the value 57 at line 4. At line 5, the address-of operator is used to retrieve the address of the variable num, and store this value in pnum. Since num resides at memory location 1000 (as is shown under the box), the value 1000 is put in pnum. pnum is now pointing to num. This has been indicated on the diagram with an arrow. Note how the variable pnum was declared in line 3. The asterisk (*) there is not the dereference operator. In this context, it is used to tell the C compiler that pnum is not an int, but is a pointer to an int (an int*). Do not think of the arrow as a pointer. It s better to think of the box pnum as the pointer. A pointer is just like any other variable; the arrow is just there to help you find the box it is pointing to. Now look at Diagram 2b. This shows the program memory when the program is finished. The dereference operator is used at line 6. *pnum tells the compiler to take the value inside pnum (which is 1000), and go get the box with that value underneath it. That box happens to be the one labeled num in this case. The rest of line 6 tells the compiler to put the value 23 inside that box. If you run this program, the number 23 will be printed. The value of num has been changed. The pointer operators There are two pointer operators: * and &. & is a unary operator that returns the memory address of its operand. You can think of & as returning the address of. The second pointer operation, *, is the complement of &. It is a unary operator that returns the value located at the address that follows. You can think of * as value at address.

3 If we declare the following: int *a, b, *c; It means that a and c is a pointer of type int, and b is simply a variable of type int. Suppose we have integral variable v and its value is 10. The variable p is declared as a pointer variable. The statement p=&v assign address of v to p. i.e. p is the pointer to variable v. The pointer p is noting but address of the variable v. To display the value stored at that location *p is used. The pointer variables also have address and are displayed using & operator. For example: printf( \n Address of v = %u, p); /* Always use %u for displaying address. */ printf( \n Address of v = %u, &v); printf( \n Value of v = %d, *p); printf( \n Value of v = %d, v); printf( \n Value of v = %d, *(&v)); printf( \n Address of p = %u, &p); So, *p means value at some address, p. And &v means address of some variable, v. p = q; /*means that address q is over-written over the address p */ *p = *q; /*means that value of address q is over-written over the address p */ p = &a; /*means that pointer p points to address of a*/ *p = a; /*means that the value at the address, at which p is already pointing, is overwritten by the value of a*/ Pointer Conversions You can use a pointer on the right-hand side of an assignment statement to assign its value to another pointer. Let us consider some of the cases: Case 1: When both pointers are of same type: The situation is straightforward. No explicit cast is required. For example, p1 = &x; //here, p1 and x are of same data type p2 = p1; //here, p2 and p1 are of same data type Case 2: Converting one type of pointer to another type, without using void * pointer: The conversion must be performed by using an explicit cast. However, the conversion of one type of pointer into another type may create undefined behavior. For example, p = (int *) &x; //here, data type of x is double Case 3: Conversion between a pointer and void * pointer:

4 A void * pointer is called a generic pointer. The void * pointer is used to specify a pointer whose base type is unknown. The void * type allows a function to specify a parameter that is capable of receiving any type of pointer argument without reporting a type mismatch. No explicit cast is required to convert to or from a void * pointer. Pointer Arithmetic There are only two arithmetic operations that you can use on pointers: Addition or subtraction of an integer to a pointer: Let p1 be an integer pointer with a current value of Also, assume ints are 2 bytes long. p1++; //p1 is jumped from 2000 to 2002 p1--; //p1 is jumped from 2000 to 1998 p1 = p1 + 10; //p1 is jumped from 2000 to 2020 p1 = p1 10; //p1 is jumped from 2000 to 1980 Subtraction of a pointer from another: You can subtract one pointer from another in order to find the number of objects of their base type that separate the two. All other arithmetic operations are prohibited. Pointer Comparisons We can compare two pointers in a relational expression. For instance, given two pointers p and q, the following statement is perfectly valid: if (p < q) printf( p points to lower memory location then q\n ); Generally, pointer comparisons are useful only when two pointers point to a common object, such as an array. Array of Pointers Pointers can be arrayed like any other data type. The declaration for an int pointer array of size is int *x[10]; To assign the address of an integer variable called var to the third element of the pointer array, write x[2] = &var; To find the value of var, write *x[2]

5 Note that there is no pre-defined relation between the address to which the elements of a array of pointer will point. So here, we are to assign the address to each of the element of array of pointers. Initializing Pointers Consider the following statements: int *p; //Declares a pointer *p = 70; //Now, that particular piece of memory has a value of 70. Now, consider the following: int *p = 70; //Declares a pointer pointing to the, first cell (having address 70), piece of memory of integral size having garbage value. So, this way we can initialize a pointer to any particular memory address. This happens because while declaration, we talk about the pointer; not about its value. A pointer that does not currently point to a valid memory location is given the value null (which is zero). Null is used because C guarantees that no object will exist at the null address. Thus, any pointer that is null implies that it points to nothing and should not be used.make a habit to define pointer while declaration, as follows: data_type *p = 0; //Now, the pointer p, points to zero-address. data_type *p = NULL; //same as above. C defines a macro NULL which means a null pointer. To use this macro, we need to include the header file <stdlib.h>. Function Pointers A function pointer is a variable that points to a function. Definition of a function pointer: returntype (*functptr)(paramtype1, paramtype2) Example: fptr is a function pointer that can point to any function that takes an int and float argument and returns a float. Assigning a function pointer float (*fptr)(int, float) float func(int i, float f) return i+f;

6 Calling a function the function pointer points to... fptr = func; // assignment ptr to function fptr(42, 3.14f); // Calling the function with the pointer C s Dynamic Allocation Functions Dynamic allocation is the means by which a program can obtain memory while it is running. Memory allocated by C s dynamic allocation functions is obtained from the heap. The heap is free memory that is not used by your program, the operating system, or any other program running in the computer. The size of heap can not usually be known in advance, but it typically contains fairly large amount of free memory. Although the size of the heap is often quite large, it is finite and can be exhausted. The core of C s allocation system consists of functions malloc() and free(). These functions work together using the free memory region to establish and maintain a list of available storage. The malloc() function allocates memory, and the free() function releases it. Any program that uses these functions must include the header <stdlib.h>. The malloc() function The malloc() functions has the prototype: void *malloc(size_t number_of_bytes); It returns a pointer of the type void *, which means that you can assign it to any type of pointer. After successful call, it returns a pointer to first byte of the region of memory of allocated from the heap. If there is not enough available memory to satisfy the malloc() request, an allocation failure occurs and malloc() returns a null. C defines (using typedef) a special type called size_t, which corresponds loosely to an unsi`gned integer. Technically, the value returned by sizeof is of type size_t. For all practical purposes, however, you can think of it (and use it) as if it were an unsigned integer value. So, if we wish to point a float pointer to a memory of size 5 times the size of float, we can write: p = (float *)malloc(5*sizeof(float)); Here, we used the type cast (float *) to convert pointer of the type (void *) to the type of the pointer to the left side of the assignment. Since the heap is not infinite, whenever you allocate memory, you must check the value returned by malloc() to make sure that it is not null before using the pointer. Using null pointer will automatically crash your

7 program. The proper way to allocate memory and test for a valid pointer is illustrated in this code fragment: p = (int *)malloc(100); if (!p) printf( Out of memory.\n ); exit(1); The free() function The free() function is the opposite of malloc() in that it returns previously allocated memory to the system. Once the memory has been freed, it may be reused by a subsequent call to malloc(). The function free() has the prototype: void free(void *p); Here, p is a pointer to the memory that was previously allocated using malloc(). It is critical that you never call free() with an invalid argument; this will damage the allocation system. It is good practice to explicitly set p to NULL after executing free(p). ARRAYS AND STRINGS Arrays: The general form of declaring a single dimension array is data _ type arr _ name[ size] ; By this we are actually declaring a pointer of data type data_type, with name arr_name. In C89, the size of an array must be specified using a constant expression(in C99 we can declare array of variable size). In C, all arrays have 0 as the index of their first element. Within index box [], we can use any expression while accessing. For example: [i+j], [i++], etc. Strings: String is an array of characters with its last meaningful character followed by NULL character. In C language the group of characters, digits, and symbols enclosed within quotation marks are called as string. There is no string type in C; strings are merely a sort of abbreviated notation for specifying character arrays. The control string of printf(), that we include with in double quotes, is just a string. For a character array to be treated as a string, its last meaningful character must be followed by the ASCII value 0, known as the

8 null character and indicated in C by \0. For example, the string review would be stored as shown in figure: r e v i e w \0 You do not need to add the null to the end of string constants manually the compiler does this for you automatically. When declaring a character array that will hold a string, you need to declare it to be one character longer than the largest string that it will hold. Length of a string is defined as the number of non-null characters it contains, so the number of locations needed to store a string is one more than the string s length. Note that one can display character string without knowing the length of the string. Every character array always ends with NULL ( \0 ) character. By using NULL character in while loop we can write a program to display the string. Note that \0 and 0 are not same. ASCII value of \0 is 0, whereas ASCII value of 0 is 48. Multidimensional arrays and strings: C supports multidimensional arrays. The simplest multi-dimensional arrays the 2-D arrays are stored in a row-column matrix, where the left index indicates the row and the right indicates the column. This means that the rightmost index changes faster than the leftmost when accessing the elements in the array in the order in which they are actually stored in memory. Some peculiar properties of Array and Strings Initialization during declaration Initialization of whole of the array (or string) can be done at once during its declaration. Declaration of an array is done as follows: [ size1] [ sizen] type _ specifier array _ name... The general form of array s definition along with declaration is similar to that of variables, as shown here: [ size1... ] [ sizen] value _ list; type _ specifier array _ name = The value _ list is a comma-separated list of constants whose type is compatible with type_specifier. Character arrays that hold strings allow a shorthand initialization that takes the form: char array _ name[ size] = " string"; For example: int marks[3] = 40, 95, 76; char Name[7] = M, u, n, i, s, h ;, or

9 char Name[7] = Munish ; Declaration and Initialization of multi-dimensional arrays (or strings): Multi-dimensional arrays are initialized the same as single-dimension ones. When initializing a multi-dimensional array, you may add braces around the initializes for each dimension. This is called sub-aggregate grouping. For example: int sqrs[3][2] = 1,1, 2,4, 3,9 When using sub-aggregate grouping, if you don t supply enough initializes for a given group, the remaining members will be set to zero, automatically. For example: char word_list[6][15] = hello, goodbye, nice day, it s raining Since only four literals are specified, all the elements of last row got null value. Unsized array initialization: If, in an array s (may be any data type) initialization statement, the size of the array is not specified, the compiler automatically creates an array big enough to hold all the initializes present. For multi-dimensional arrays, you must specify all but the leftmost dimension. Accessing Arrays and Strings, after declaration Overwriting the values of 1-D Array and String: We already know that an array name is pointer of data type data_type to the first cell (of size corresponding to the data type) of the arbitrarily fixed continuous array of unused cells, of size size. This pointer is just as another pointer, so we access arrays as if we know a pointer to starting cell of array of cells. After declaration, while giving values to array, each element must be specified. For example: scanf( %d %d %d, a[0], a[1], a[2]); For string there are some inbuilt functions, where input is given in pointers that ease our job. For example: gets(name); (Note that Name is a pointer to a string) Overwriting the values of Multi-dimensional Array and Strings: Singly indexed name of 2-D array (or string) acts as pointer to corresponding part of the array. For a array of string, we can get each string individually. It is easy to access an individual string: We simply specify only the left index. For example, the following statement calls gets() with the third string in str_array. gets(str_array[2]); //for scanning whole of the particular string

10 Read out Similarly, we can not print all elements of an array as; printf( %d, a);, instead we are to write following: printf( %d %d %d, a[0], a[1], a[2]); The following command displays starting address of the array: printf( %u, a); Unlike arrays, you can print all the elements of a string at once as follows: puts(name); Note that the following command will print whole of the string Name except its first 2 elements: puts(name + 2); // Name+2 pointer points to 3 rd element of string We can also print it as we do for arrays, as: printf( %c%c%c%c%c%c, Name[0],Name[1],Name[2],Name[3],Name[4],Name[5]); Accessing array elements Values to array elements can be given as follows: a[1] = 6; etc a[2] = a[1]; a[++i] = k; *((int *)a + 1) = 6; Passing arrays Assigning the values of one array to another An entire array cannot be assigned to another array because we have no variable that stands for whole of the array. Each element of x must be assigned separately to the corresponding element of y. Passing 1-D Array to Functions In C, we cannot pass an entire array as an argument to a function. We can, however, pass a pointer to an array by specifying the array s name without and index. For example: fucnt1(a); If a function receives a pointer to a single-dimension array, we can declare its parameter in one of three ways: i) As a pointer: (int *x) ii) As a sized array: (int x[5]) iii) As an un-sized array: (int x[])

11 Note that in all the three cases, we are assigning address of pointer a to pointer x. Pointer types and Arrays Okay, let's move on. Let us consider why we need to identify the type of variable that a pointer points to, as in: int *ptr; One reason for doing this is so that later, once ptr "points to" something, if we write: *ptr = 2; the compiler will know how many bytes to copy into that memory location pointed to by ptr. If ptr was declared as pointing to an integer, 4 bytes would be copied. Similarly for floats and doubles the appropriate number will be copied. But, defining the type that the pointer points to permits a number of other interesting ways a compiler can interpret code. For example, consider a block in memory consisting if ten integers in a row. That is, 40 bytes of memory are set aside to hold 10 integers. Now, let's say we point our integer pointer ptr at the first of these integers. Furthermore lets say that integer is located at memory location 100 (decimal). What happens when we write: ptr + 1; Because the compiler "knows" this is a pointer (i.e. its value is an address) and that it points to an integer (its current address, 100, is the address of an integer), it adds 4 to ptr instead of 1, so the pointer "points to" the next integer, at memory location 104. Similarly, were the ptr declared as a pointer to a short, it would add 2 to it instead of 1. The same goes for other data types such as floats, doubles, or even user defined data types such as structures. This is obviously not the same kind of "addition" that we normally think of. In C it is referred to as addition using "pointer arithmetic", a term which we will come back to later. Similarly, since ++ptr and ptr++ are both equivalent to ptr + 1 (though the point in the program when ptr is incremented may be different), incrementing a pointer using the unary ++ operator, either pre- or post-, increments the address it stores by the amount sizeof(type) where "type" is the type of the object pointed to. (i.e. 4 for an integer). Since a block of 10 integers located contiguously in memory is, by definition, an array of integers, this brings up an interesting relationship between arrays and pointers. Consider the following: int my_array[] = 1,23,17,4,-5,100;

12 Here we have an array containing 6 integers. We refer to each of these integers by means of a subscript to my_array, i.e. using my_array[0] through my_array[5]. But, we could alternatively access them via a pointer as follows: int *ptr; ptr = &my_array[0]; /* point our pointer at the first integer in our array */ And then we could print out our array either using the array notation or by dereferencing our pointer. The following code illustrates this: Sample Program #include <stdio.h> int my_array[] = 1,23,17,4,-5,100; int *ptr; int main(void) int i; ptr = &my_array[0]; /* point our pointer to the first element of the array */ printf("\n\n"); for (i = 0; i < 6; i++) printf("my_array[%d] = %d ",i,my_array[i]); /*<-- A */ printf("ptr + %d = %d\n",i, *(ptr + i)); /*<-- B */ return 0; Compile and run the above program and carefully note lines A and B and that the program prints out the same values in either case. Also observe how we dereferenced our pointer in line B, i.e. we first added i to it and then dereferenced the new pointer. Change line B to read: printf("ptr + %d = %d\n",i, *ptr++); and run it again... then change it to: printf("ptr + %d = %d\n",i, *(++ptr));

13 and try once more. Each time try and predict the outcome and carefully look at the actual outcome. In C, the standard states that wherever we might use &var_name[0] we can replace that with var_name, thus in our code where we wrote: ptr = &my_array[0]; we can write: ptr = my_array; to achieve the same result. This leads many texts to state that the name of an array is a pointer. I prefer to mentally think "the name of the array is the address of first element in the array". Many beginners (including myself when I was learning) have a tendency to become confused by thinking of it as a pointer. For example, while we can write, ptr = my_array; we cannot write : my_array = ptr; The reason is that while ptr is a variable, my_array is a constant. That is, the location at which the first element of my_array will be stored cannot be changed once my_array[] has been declared. Now, let's delve a little further into the difference between the names ptr and my_array as used above. Some writers will refer to an array's name as a constant pointer. What do we mean by that? Well, to understand the term "constant" in this sense, let's go back to our definition of the term "variable". When we declare a variable we set aside a spot in memory to hold the value of the appropriate type. Once that is done the name of the variable can be interpreted in one of two ways. When used on the left side of the assignment operator, the compiler interprets it as the memory location to which to move that value resulting from evaluation of the right side of the assignment operator. But, when used on the right side of the assignment operator, the name of a variable is interpreted to mean the contents stored at that memory address set aside to hold the value of that variable. With that in mind, let's now consider the simplest of constants, as in: int i, k; i = 2; Here, while i is a variable and then occupies space in the data portion of memory, 2 is a constant and, as such, instead of setting aside memory in the data segment, it is imbedded directly in the code segment of memory. That is, while writing something like k = i; tells the compiler to create code which at run time will look at memory location &i to determine the value to be moved to k, code created by i = 2; simply puts the 2 in the code

14 and there is no referencing of the data segment. That is, both k and i are objects, but 2 is not an object. Similarly, in the above, since my_array is a constant, once the compiler establishes where the array itself is to be stored, it "knows" the address of my_array[0] and on seeing: ptr = my_array; It simply uses this address as a constant in the code segment and there is no referencing of the data segment beyond that. This might be a good place explain further the use of the (void *) expression. As we have seen we can have pointers of various types. So far we have discussed pointers to integers and pointers to characters. In coming chapters we will be learning about pointers to structures and even pointer to pointers. Also we have learned that on different systems the size of a pointer can vary. As it turns out it is also possible that the size of a pointer can vary depending on the data type of the object to which it points. Thus, as with integers where you can run into trouble attempting to assign a long integer to a variable of type short integer, you can run into trouble attempting to assign the values of pointers of various types to pointer variables of other types. To minimize this problem, C provides for a pointer of type void. We can declare such a pointer by writing: void *vptr; Pointers and Strings The study of strings is useful to further tie in the relationship between pointers and arrays. It also makes it easy to illustrate how some of the standard C string functions can be implemented. Finally it illustrates how and when pointers can and should be passed to functions. In C, strings are arrays of characters. This is not necessarily true in other languages. In BASIC, Pascal, Fortran and various other languages, a string has its own data type. But in C it does not. In C a string is an array of characters terminated with a binary zero character (written as '\0'). To start off our discussion we will write some code which, while preferred for illustrative purposes, you would probably never write in an actual program. Consider, for example: char my_string[40]; my_string[0] = 'T'; my_string[1] = 'e'; my_string[2] = 'd': my_string[3] = '\0';

15 While one would never build a string like this, the end result is a string in that it is an array of characters terminated with a nul character. By definition, in C, a string is an array of characters terminated with the nul character. Be aware that "nul" is not the same as "NULL". The nul refers to a zero as defined by the escape sequence '\0'. That is it occupies one byte of memory. NULL, on the other hand, is the name of the macro used to initialize null pointers. NULL is #defined in a header file in your C compiler, nul may not be #defined at all. Since writing the above code would be very time consuming, C permits two alternate ways of achieving the same thing. First, one might write: char my_string[40] = 'T', 'e', 'd', '\0',; But this also takes more typing than is convenient. So, C permits: char my_string[40] = "Ted"; When the double quotes are used, instead of the single quotes as was done in the previous examples, the nul character ( '\0' ) is automatically appended to the end of the string. In all of the above cases, the same thing happens. The compiler sets aside an contiguous block of memory 40 bytes long to hold characters and initialized it such that the first 4 characters are Ted\0. Now, consider the following program: program #include <stdio.h> char stra[80] = "A string to be used for demonstration purposes"; char strb[80]; int main(void) char *pa; /* a pointer to type character */ char *pb; /* another pointer to type character */ puts(stra); /* show string A */ pa = stra; /* point pa at string A */ puts(pa); /* show what pa is pointing to */ pb = strb; /* point pb at string B */ putchar('\n'); /* move down one line on the screen */ while(*pa!= '\0') /* line A (see text) */ *pb++ = *pa++; /* line B (see text) */

16 *pb = '\0'; /* line C (see text) */ puts(strb); /* show strb on screen */ return 0; In the above we start out by defining two character arrays of 80 characters each. Since these are globally defined, they are initialized to all '\0's first. Then, stra has the first 42 characters initialized to the string in quotes. Now, moving into the code, we declare two character pointers and show the string on the screen. We then "point" the pointer pa at stra. That is, by means of the assignment statement we copy the address of stra[0] into our variable pa. We now use puts() to show that which is pointed to by pa on the screen. Consider here that the function prototype for puts() is: int puts(const char *s); For the moment, ignore the const. The parameter passed to puts() is a pointer, that is the value of a pointer (since all parameters in C are passed by value), and the value of a pointer is the address to which it points, or, simply, an address. Thus when we write puts(stra); as we have seen, we are passing the address of stra[0]. Similarly, when we write puts(pa); we are passing the same address, since we have set pa = stra; Given that, follow the code down to the while() statement on line A. Line A states: While the character pointed to by pa (i.e. *pa) is not a nul character (i.e. the terminating '\0'), do the following: Line B states: copy the character pointed to by pa to the space pointed to by pb, then increment pa so it points to the next character and pb so it points to the next space. When we have copied the last character, pa now points to the terminating nul character and the loop ends. However, we have not copied the nul character. And, by definition a string in C must be nul terminated. So, we add the nul character with line C. It is very educational to run this program with your debugger while watching stra, strb, pa and pb and single stepping through the program. It is even more educational if instead of simply defining strb[] as has been done above, initialize it also with something like: strb[80] = " "

17 where the number of digits used is greater than the length of stra and then repeat the single stepping procedure while watching the above variables. Give these things a try! Getting back to the prototype for puts() for a moment, the "const" used as a parameter modifier informs the user that the function will not modify the string pointed to by s, i.e. it will treat that string as a constant. Of course, what the above program illustrates is a simple way of copying a string. After playing with the above until you have a good understanding of what is happening, we can proceed to creating our own replacement for the standard strcpy() that comes with C. It might look like: char *my_strcpy(char *destination, char *source) char *p = destination; while (*source!= '\0') *p++ = *source++; *p = '\0'; return destination; In this case, I have followed the practice used in the standard routine of returning a pointer to the destination. Again, the function is designed to accept the values of two character pointers, i.e. addresses, and thus in the previous program we could write: int main(void) my_strcpy(strb, stra); puts(strb); I have deviated slightly from the form used in standard C which would have the prototype: char *my_strcpy(char *destination, const char *source); Here the "const" modifier is used to assure the user that the function will not modify the contents pointed to by the source pointer. You can prove this by modifying the function above, and its prototype, to include the "const" modifier as shown. Then, within the

18 function you can add a statement which attempts to change the contents of that which is pointed to by source, such as: *source = 'X'; which would normally change the first character of the string to an X. The const modifier should cause your compiler to catch this as an error. Try it and see. Now, let's consider some of the things the above examples have shown us. First off, consider the fact that *ptr++ is to be interpreted as returning the value pointed to by ptr and then incrementing the pointer value. This has to do with the precedence of the operators. Were we to write (*ptr)++ we would increment, not the pointer, but that which the pointer points to! i.e. if used on the first character of the above example string the 'T' would be incremented to a 'U'. You can write some simple example code to illustrate this. Recall again that a string is nothing more than an array of characters, with the last character being a '\0'. What we have done above is deal with copying an array. It happens to be an array of characters but the technique could be applied to an array of integers, doubles, etc. In those cases, however, we would not be dealing with strings and hence the end of the array would not be marked with a special value like the nul character. We could implement a version that relied on a special value to identify the end. For example, we could copy an array of positive integers by marking the end with a negative integer. On the other hand, it is more usual that when we write a function to copy an array of items other than strings we pass the function the number of items to be copied as well as the address of the array, e.g. something like the following prototype might indicate: void int_copy(int *ptra, int *ptrb, int nbr); where nbr is the number of integers to be copied. You might want to play with this idea and create an array of integers and see if you can write the function int_copy() and make it work. This permits using functions to manipulate large arrays. For example, if we have an array of 5000 integers that we want to manipulate with a function, we need only pass to that function the address of the array (and any auxiliary information such as nbr above, depending on what we are doing). The array itself does not get passed, i.e. the whole array is not copied and put on the stack before calling the function, only its address is sent. This is different from passing, say an integer, to a function. When we pass an integer we make a copy of the integer, i.e. get its value and put it on the stack. Within the function any manipulation of the value passed can in no way effect the original integer.

19 But, with arrays and pointers we can pass the address of the variable and hence manipulate the original values. More on Strings Well, we have progressed quite a way in a short time! Let's back up a little and look at what was done in Chapter 3 on copying of strings but in a different light. Consider the following function: char *my_strcpy(char dest[], char source[]) int i = 0; while (source[i]!= '\0') dest[i] = source[i]; i++; dest[i] = '\0'; return dest; Recall that strings are arrays of characters. Here we have chosen to use array notation instead of pointer notation to do the actual copying. The results are the same, i.e. the string gets copied using this notation just as accurately as it did before. This raises some interesting points which we will discuss. Since parameters are passed by value, in both the passing of a character pointer or the name of the array as above, what actually gets passed is the address of the first element of each array. Thus, the numerical value of the parameter passed is the same whether we use a character pointer or an array name as a parameter. This would tend to imply that somehow source[i] is the same as *(p+i). In fact, this is true, i.e wherever one writes a[i] it can be replaced with *(a + i) without any problems. In fact, the compiler will create the same code in either case. Thus we see that pointer arithmetic is the same thing as array indexing. Either syntax produces the same result. This is NOT saying that pointers and arrays are the same thing, they are not. We are only saying that to identify a given element of an array we have the choice of two syntaxes, one using array indexing and the other using pointer arithmetic, which yield identical results. Now, looking at this last expression, part of it.. (a + i), is a simple addition using the + operator and the rules of C state that such an expression is

20 commutative. That is (a + i) is identical to (i + a). Thus we could write *(i + a) just as easily as *(a + i). But *(i + a) could have come from i[a]! From all of this comes the curious truth that if: char a[20]; int i; writing a[3] = 'x'; is the same as writing 3[a] = 'x'; Try it! Set up an array of characters, integers or longs, etc. and assigned the 3rd or 4th element a value using the conventional approach and then print out that value to be sure you have that working. Then reverse the array notation as I have done above. A good compiler will not balk and the results will be identical. A curiosity... nothing more! Now, looking at our function above, when we write: dest[i] = source[i]; due to the fact that array indexing and pointer arithmetic yield identical results, we can write this as: *(dest + i) = *(source + i); But, this takes 2 additions for each value taken on by i. Additions, generally speaking, take more time than incrementations (such as those done using the ++ operator as in i++). This may not be true in modern optimizing compilers, but one can never be sure. Thus, the pointer version may be a bit faster than the array version. Another way to speed up the pointer version would be to change: while (*source!= '\0') to simply while (*source) since the value within the parenthesis will go to zero (FALSE) at the same time in either case. At this point you might want to experiment a bit with writing some of your own programs using pointers. Manipulating strings is a good place to experiment. You might want to write your own versions of such standard functions as: strlen(); strcat(); strchr();

21 and any others you might have on your system. We will come back to strings and their manipulation through pointers in a future chapter. For now, let's move on and discuss structures for a bit. STRUCTURES Declaration of a Structure A structure is a definition of new a data-type. It contains a number of old data-types grouped together. These data-types may or may not be of the same type. The general form of a structure is given below (definition of new-data type): struct <struct_name> Declaration of <structure_element_1>; Declaration of <structure_element_2>; ; Once the new structure data-type has been defined one or more variables can be declared to be of that type. Now, struct <struct_name> will start functioning as new-data type. struct <struct_name> <structure_variables_1>,, <structure_variable_n> ; Initializing a structural variable Like primary variables and arrays, structure-variables can also be initialized where they are declared. The format used is quite similar to that used to initiate arrays. struct book char name[10]; float price; int pages; ; struct book b1 = Basic, , 550; struct book b2 = Physics, , 800; Note that the definitions like above, can be done only during declaration. The structure variables to which definition is to be done, should not be part of array of structure

22 variables.whatever be the elements of a structure, they are always stored in contiguous memory locations. Accessing Structure-variable s elements In arrays we can access individual elements of an array using a subscript. Structures use a different scheme. They use a dot (.) operator. So to refer to pages of book b1 we have to use; b1.pages That is, <structure_variable>.<structure_element> We can treat it as our simple variable (just forget <structure_variable> and dot-operator) Array of structure The way of declaring and accessing an array of structures is given below: Declaration: struct book char name[10]; float price; unsigned int pages; ; struct book b[50]; Accessing: int i; for (i=0, i<=49, i++) printf( \nenter name, prices and pages ); scanf( %c %f %u, &b[i].name, &b[i].price, &b[i].pages); Additional features Assigning one structure variable to another The value of a structure variable can be assigned to another structure variable of the same type using the assignment operator. We do not need to assign the value of each member separately. Both structures must be of same structure-type.

23 Passing a structure variable to a function When a structure-variable is used as an argument to a function, the entire structure-variable is passed using the normal call-by-value method. When using a structure as a parameter, remember that the type of the argument must match the type of the parameter. It is not sufficient for them simply to be physically similar; their type names must match. Thus in this case, structure definition should be global, and both argument and parameter structures should be of structure-type defined globally. Nesting of structures One structure can be nested within another structure. Using this facility complex data types can be created. main() struct address char phone[15]; char city[25]; int pin; ; struct emp char name[25]; struct address a; struct emp e = jeru, , nagpur, 10; printf( \ncity = %s pin = %d, e.a.city, e.a.pin); Pointers and Structures As you may know, we can declare the form of a block of data containing different data types by means of a structure declaration. For example, a personnel file might contain structures which look something like: struct tag char lname[20]; /* last name */

24 char fname[20]; /* first name */ int age; /* age */ float rate; /* e.g per hour */ ; Let's say we have a bunch of these structures in a disk file and we want to read each one out and print out the first and last name of each one so that we can have a list of the people in our files. The remaining information will not be printed out. We will want to do this printing with a function call and pass to that function a pointer to the structure at hand. For demonstration purposes I will use only one structure for now. But realize the goal is the writing of the function, not the reading of the file which, presumably, we know how to do. For review, recall that we can access structure members with the dot operator as in: program #include <stdio.h> #include <string.h> struct tag char lname[20]; /* last name */ char fname[20]; /* first name */ int age; /* age */ float rate; /* e.g per hour */ ; struct tag my_struct; /* declare the structure my_struct */ int main(void) strcpy(my_struct.lname,"jensen"); strcpy(my_struct.fname,"ted"); printf("\n%s ",my_struct.fname); printf("%s\n",my_struct.lname); return 0; Now, this particular structure is rather small compared to many used in C programs. To the above we might want to add:

25 date_of_hire; (data types not shown) date_of_last_raise; last_percent_increase; emergency_phone; medical_plan; Social_S_Nbr; etc... If we have a large number of employees, what we want to do is manipulate the data in these structures by means of functions. For example we might want a function print out the name of the employee listed in any structure passed to it. However, in the original C (Kernighan & Ritchie, 1st Edition) it was not possible to pass a structure, only a pointer to a structure could be passed. In ANSI C, it is now permissible to pass the complete structure. But, since our goal here is to learn more about pointers, we won't pursue that. Anyway, if we pass the whole structure it means that we must copy the contents of the structure from the calling function to the called function. In systems using stacks, this is done by pushing the contents of the structure on the stack. With large structures this could prove to be a problem. However, passing a pointer uses a minimum amount of stack space. In any case, since this is a discussion of pointers, we will discuss how we go about passing a pointer to a structure and then using it within the function. Consider the case described, i.e. we want a function that will accept as a parameter a pointer to a structure and from within that function we want to access members of the structure. For example we want to print out the name of the employee in our example structure. Okay, so we know that our pointer is going to point to a structure declared using struct tag. We declare such a pointer with the declaration: struct tag *st_ptr; and we point it to our example structure with: st_ptr = &my_struct; Now, we can access a given member by de-referencing the pointer. But, how do we dereference the pointer to a structure? Well, consider the fact that we might want to use the pointer to set the age of the employee. We would write: (*st_ptr).age = 63;

26 Look at this carefully. It says, replace that within the parenthesis with that which st_ptr points to, which is the structure my_struct. Thus, this breaks down to the same as my_struct.age. However, this is a fairly often used expression and the designers of C have created an alternate syntax with the same meaning which is: st_ptr->age = 63; With that in mind, look at the following program: program #include <stdio.h> #include <string.h> struct tag /* the structure type */ char lname[20]; /* last name */ char fname[20]; /* first name */ int age; /* age */ float rate; /* e.g per hour */ ; struct tag my_struct; /* define the structure */ void show_name(struct tag *p); /* function prototype */ int main(void) struct tag *st_ptr; /* a pointer to a structure */ st_ptr = &my_struct; /* point the pointer to my_struct */ strcpy(my_struct.lname,"jensen"); strcpy(my_struct.fname,"ted"); printf("\n%s ",my_struct.fname); printf("%s\n",my_struct.lname); my_struct.age = 63; show_name(st_ptr); /* pass the pointer */ return 0; void show_name(struct tag *p)

27 printf("\n%s ", p->fname); /* p points to a structure */ printf("%s ", p->lname); printf("%d\n", p->age); Again, this is a lot of information to absorb at one time. The reader should compile and run the various code snippets and using a debugger monitor things like my_struct and p while single stepping through the main and following the code down into the function to see what is happening. The typedef You can define new data type names by using the keyword typedef. You are not actually creating a new data type, but rather defining a new name for an existing type. The general form of typedef statement is: typedef type new_name; where, type is any valid data type, and new_name is the new name (preferably in CAPS) for this type. The new name you define is in addition to, not a replacement for, the existing type name. For example: typedef float BALANCE; typedef struct node *NODE; This statement tells the compiler to recognize BALANCE as another name for float. Next, you could create a float variable using BALANCE; BALANCE over_due; NODE p; //Here, p is a pointer of the type (strut node *). Now the BALANCE has been defined, it can be used in another typedef. typedef BALANCE OVERDRAFT; FILES We frequently use files for storing information which can be processed by our programs. In order to store information permanently and retrieve it, we need to use files. Files are not only used for data. Our programs are also stored in files. The editor which you use to enter your program and save, simply manipulates files for you. In order to use files we have to learn about File I/O i.e. how to write information to a file and how to read information from a file. We will see that file I/O is almost identical to the terminal I/O that we have being using so far. The

28 primary difference between manipulating files and doing terminal I/O is that we must specify in our programs which files we wish to use. As you know, you can have many files on your disk. If you wish to use a file in your programs, then you must specify which file or files you wish to use. Specifying the file you wish to use is referred to as opening the file. When you open a file you must also specify what you wish to do with it i.e. Read from the file, Write to the file, or both. Because you may use a number of different files in your program, you must specify when reading or writing which file we want to use. This is accomplished by using a variable called a file pointer. Every file you open has its own file pointer variable. When you wish to write to a file you specify the file by using its file pointer variable. You declare these file pointer variables as follows: FILE *fopen(), *fp1, *fp2, *fp3; The variables fp1, fp2, fp3 are file pointers. You may use any name you wish. The file <stdio.h> contains declarations for the Standard I/O library and should always be included at the very beginning of C programs using files. Constants such as FILE, EOF and NULL are defined in <stdio.h>. You should note that a file pointer is simply a variable like an integer or character. It does not point to a file or the data in a file. It is simply used to indicate which file your I/O operation refers to. A file number is used in the Basic language and a unit number is used in Fortran for the same purpose. The function fopen is one of the Standard Library functions and returns a file pointer which you use to refer to the file you have opened e.g. fp = fopen( prog.c, r ) ; The above statement opens a file called prog.c for reading and associates the file pointer fp with the file. When we wish to access this file for I/O, we use the file pointer variable fp to refer to it. You can have up to about 20 files open in your program - you need one file pointer for each file you intend to use. File I/O The Standard I/O Library provides similar routines for file I/O similar to that of standard I/O. The routine getc(fp) is similar to getchar() and putc(c,fp) is similar to putchar(c). Thus the statement c = getc(fp); ---- reads the next character from the file referenced by fp and the statement putc(c,fp); --- writes the character c into file referenced by fp.

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8 Pointers Variables vs. Pointers: A variable in a program is something with a name and a value that can vary. The way the compiler and linker handles this is that it assigns a specific block of memory within

More information

Programming. Pointers, Multi-dimensional Arrays and Memory Management

Programming. Pointers, Multi-dimensional Arrays and Memory Management Programming Pointers, Multi-dimensional Arrays and Memory Management Summary } Computer Memory } Pointers } Declaration, assignment, arithmetic and operators } Casting and printing pointers } Relationship

More information

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36 Department of Computer Science College of Engineering Boise State University August 25, 2017 1/36 Pointers and Arrays A pointer is a variable that stores the address of another variable. Pointers are similar

More information

CSCI 171 Chapter Outlines

CSCI 171 Chapter Outlines Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures

More information

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size]; Arrays An array is a collection of two or more adjacent memory cells, called array elements. Array is derived data type that is used to represent collection of data items. C Array is a collection of data

More information

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology Introduction to C++ Massachusetts Institute of Technology ocw.mit.edu 6.096 Pointers 1 Background 1.1 Variables and Memory When you declare a variable, the computer associates the variable name with a

More information

Lecture 04 Introduction to pointers

Lecture 04 Introduction to pointers Lecture 04 Introduction to pointers A pointer is an address in the memory. One of the unique advantages of using C is that it provides direct access to a memory location through its address. A variable

More information

Model Viva Questions for Programming in C lab

Model Viva Questions for Programming in C lab Model Viva Questions for Programming in C lab Title of the Practical: Assignment to prepare general algorithms and flow chart. Q1: What is a flowchart? A1: A flowchart is a diagram that shows a continuous

More information

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University Unit 1 Programming Language and Overview of C 1. State whether the following statements are true or false. a. Every line in a C program should end with a semicolon. b. In C language lowercase letters are

More information

https://www.eskimo.com/~scs/cclass/notes/sx8.html

https://www.eskimo.com/~scs/cclass/notes/sx8.html 1 de 6 20-10-2015 10:41 Chapter 8: Strings Strings in C are represented by arrays of characters. The end of the string is marked with a special character, the null character, which is simply the character

More information

by Pearson Education, Inc. All Rights Reserved.

by Pearson Education, Inc. All Rights Reserved. Let s improve the bubble sort program of Fig. 6.15 to use two functions bubblesort and swap. Function bubblesort sorts the array. It calls function swap (line 51) to exchange the array elements array[j]

More information

Write a C program using arrays and structure

Write a C program using arrays and structure 03 Arrays and Structutes 3.1 Arrays Declaration and initialization of one dimensional, two dimensional and character arrays, accessing array elements. (10M) 3.2 Declaration and initialization of string

More information

Structures in C. Rab Nawaz Jadoon DCS. Assistant Professor. Department of Computer Science. COMSATS IIT, Abbottabad Pakistan

Structures in C. Rab Nawaz Jadoon DCS. Assistant Professor. Department of Computer Science. COMSATS IIT, Abbottabad Pakistan Structures in C DCS COMSATS Institute of Information Technology Rab Nawaz Jadoon Assistant Professor COMSATS IIT, Abbottabad Pakistan Introduction to Computer Programming (ICP) Structures in C Which mechanic

More information

Pointers, Dynamic Data, and Reference Types

Pointers, Dynamic Data, and Reference Types Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation The new operator The delete operator Dynamic Memory Allocation for Arrays 1 C++ Data Types simple

More information

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are: LESSON 1 FUNDAMENTALS OF C The purpose of this lesson is to explain the fundamental elements of the C programming language. C like other languages has all alphabet and rules for putting together words

More information

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21 Department of Computer Science College of Engineering Boise State University September 11, 2017 1/21 Pointers A pointer is a variable that stores the address of another variable. Pointers are similar to

More information

Actually, C provides another type of variable which allows us to do just that. These are called dynamic variables.

Actually, C provides another type of variable which allows us to do just that. These are called dynamic variables. When a program is run, memory space is immediately reserved for the variables defined in the program. This memory space is kept by the variables until the program terminates. These variables are called

More information

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming Jagannath Institute of Management Sciences Lajpat Nagar BCA II Sem C Programming UNIT I Pointers: Introduction to Pointers, Pointer Notation,Decalaration and Initialization, Accessing variable through

More information

ARRAYS(II Unit Part II)

ARRAYS(II Unit Part II) ARRAYS(II Unit Part II) Array: An array is a collection of two or more adjacent cells of similar type. Each cell in an array is called as array element. Each array should be identified with a meaningful

More information

printf( Please enter another number: ); scanf( %d, &num2);

printf( Please enter another number: ); scanf( %d, &num2); CIT 593 Intro to Computer Systems Lecture #13 (11/1/12) Now that we've looked at how an assembly language program runs on a computer, we're ready to move up a level and start working with more powerful

More information

Computers Programming Course 5. Iulian Năstac

Computers Programming Course 5. Iulian Năstac Computers Programming Course 5 Iulian Năstac Recap from previous course Classification of the programming languages High level (Ada, Pascal, Fortran, etc.) programming languages with strong abstraction

More information

COMP26120: Pointers in C (2018/19) Lucas Cordeiro

COMP26120: Pointers in C (2018/19) Lucas Cordeiro COMP26120: Pointers in C (2018/19) Lucas Cordeiro lucas.cordeiro@manchester.ac.uk Organisation Lucas Cordeiro (Senior Lecturer, FM Group) lucas.cordeiro@manchester.ac.uk Office: 2.44 Office hours: 10-11

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering

More information

A Fast Review of C Essentials Part I

A Fast Review of C Essentials Part I A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types

More information

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #34. Function with pointer Argument

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #34. Function with pointer Argument Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #34 Function with pointer Argument (Refer Slide Time: 00:05) So, here is the stuff that we have seen about pointers.

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language 1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC

More information

Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100

Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100 Code: DC-05 Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100 NOTE: There are 11 Questions in all. Question 1 is compulsory and carries 16 marks. Answer to Q. 1. must be written in the space

More information

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010 CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011 Lectures 1-22 Moaaz Siddiq Asad Ali Latest Mcqs MIDTERM EXAMINATION Spring 2010 Question No: 1 ( Marks: 1 ) - Please

More information

Lectures 5-6: Introduction to C

Lectures 5-6: Introduction to C Lectures 5-6: Introduction to C Motivation: C is both a high and a low-level language Very useful for systems programming Faster than Java This intro assumes knowledge of Java Focus is on differences Most

More information

INTRODUCTION 1 AND REVIEW

INTRODUCTION 1 AND REVIEW INTRODUTION 1 AND REVIEW hapter SYS-ED/ OMPUTER EDUATION TEHNIQUES, IN. Programming: Advanced Objectives You will learn: Program structure. Program statements. Datatypes. Pointers. Arrays. Structures.

More information

Ar r ays and Pointer s

Ar r ays and Pointer s Ar r ays and Pointer s Using Bloodshed Dev-C++ Heejin Park Hanyang University 2 Introduction Arrays Multidimensional Arrays Pointers and Arrays Functions, Arrays, and Pointers Pointer Operations Protecting

More information

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW IMPORTANT QUESTIONS IN C FOR THE INTERVIEW 1. What is a header file? Header file is a simple text file which contains prototypes of all in-built functions, predefined variables and symbolic constants.

More information

COMPUTER APPLICATION

COMPUTER APPLICATION Total No. of Printed Pages 16 HS/XII/A.Sc.Com/CAP/14 2 0 1 4 COMPUTER APPLICATION ( Science / Arts / Commerce ) ( Theory ) Full Marks : 70 Time : 3 hours The figures in the margin indicate full marks for

More information

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays C Arrays This handout was written by Nick Parlante and Julie Zelenski. As you recall, a C array is formed by laying out all the elements

More information

Lectures 5-6: Introduction to C

Lectures 5-6: Introduction to C Lectures 5-6: Introduction to C Motivation: C is both a high and a low-level language Very useful for systems programming Faster than Java This intro assumes knowledge of Java Focus is on differences Most

More information

Procedural programming with C

Procedural programming with C Procedural programming with C Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada August 11, 2016 1 / 77 Functions Similarly to its mathematical

More information

Review of the C Programming Language for Principles of Operating Systems

Review of the C Programming Language for Principles of Operating Systems Review of the C Programming Language for Principles of Operating Systems Prof. James L. Frankel Harvard University Version of 7:26 PM 4-Sep-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights

More information

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018 CS 31: Intro to Systems Pointers and Memory Kevin Webb Swarthmore College October 2, 2018 Overview How to reference the location of a variable in memory Where variables are placed in memory How to make

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 9 Pointer Department of Computer Engineering 1/46 Outline Defining and using Pointers

More information

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT C Review MaxMSP Developers Workshop Summer 2009 CNMAT C Syntax Program control (loops, branches): Function calls Math: +, -, *, /, ++, -- Variables, types, structures, assignment Pointers and memory (***

More information

Pointers and File Handling

Pointers and File Handling 1 Pointers and File Handling From variables to their addresses Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR 2 Basics of Pointers INDIAN INSTITUTE OF TECHNOLOGY

More information

We do not teach programming

We do not teach programming We do not teach programming We do not teach C Take a course Read a book The C Programming Language, Kernighan, Richie Georgios Georgiadis Negin F.Nejad This is a brief tutorial on C s traps and pitfalls

More information

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University C Programming Notes Dr. Karne Towson University Reference for C http://www.cplusplus.com/reference/ Main Program #include main() printf( Hello ); Comments: /* comment */ //comment 1 Data Types

More information

These are reserved words of the C language. For example int, float, if, else, for, while etc.

These are reserved words of the C language. For example int, float, if, else, for, while etc. Tokens in C Keywords These are reserved words of the C language. For example int, float, if, else, for, while etc. Identifiers An Identifier is a sequence of letters and digits, but must start with a letter.

More information

Reserved Words and Identifiers

Reserved Words and Identifiers 1 Programming in C Reserved Words and Identifiers Reserved word Word that has a specific meaning in C Ex: int, return Identifier Word used to name and refer to a data element or object manipulated by the

More information

DECLARAING AND INITIALIZING POINTERS

DECLARAING AND INITIALIZING POINTERS DECLARAING AND INITIALIZING POINTERS Passing arguments Call by Address Introduction to Pointers Within the computer s memory, every stored data item occupies one or more contiguous memory cells (i.e.,

More information

Review of the C Programming Language

Review of the C Programming Language Review of the C Programming Language Prof. James L. Frankel Harvard University Version of 11:55 AM 22-Apr-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights reserved. Reference Manual for the

More information

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee C Language Part 1 (Minor modifications by the instructor) References C for Python Programmers, by Carl Burch, 2011. http://www.toves.org/books/cpy/ The C Programming Language. 2nd ed., Kernighan, Brian,

More information

Computer Programming Unit 3

Computer Programming Unit 3 POINTERS INTRODUCTION Pointers are important in c-language. Some tasks are performed more easily with pointers such as dynamic memory allocation, cannot be performed without using pointers. So it s very

More information

First of all, it is a variable, just like other variables you studied

First of all, it is a variable, just like other variables you studied Pointers: Basics What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the address (rather than the value)

More information

IECD Institute for Entrepreneurship and Career Development Bharathidasan University, Tiruchirappalli 23.

IECD Institute for Entrepreneurship and Career Development Bharathidasan University, Tiruchirappalli 23. Subject code - CCP01 Chapt Chapter 1 INTRODUCTION TO C 1. A group of software developed for certain purpose are referred as ---- a. Program b. Variable c. Software d. Data 2. Software is classified into

More information

Fundamentals of Programming

Fundamentals of Programming Fundamentals of Programming Lecture 3 - Constants, Variables, Data Types, And Operations Lecturer : Ebrahim Jahandar Borrowed from lecturer notes by Omid Jafarinezhad Outline C Program Data types Variables

More information

Understanding Pointers

Understanding Pointers Division of Mathematics and Computer Science Maryville College Pointers and Addresses Memory is organized into a big array. Every data item occupies one or more cells. A pointer stores an address. A pointer

More information

Computer System and programming in C

Computer System and programming in C 1 Basic Data Types Integral Types Integers are stored in various sizes. They can be signed or unsigned. Example Suppose an integer is represented by a byte (8 bits). Leftmost bit is sign bit. If the sign

More information

CIS 2107 Computer Systems and Low-Level Programming Fall 2011 Midterm

CIS 2107 Computer Systems and Low-Level Programming Fall 2011 Midterm Fall 2011 Name: Page Points Score 1 5 2 10 3 10 4 7 5 8 6 15 7 4 8 7 9 16 10 18 Total: 100 Instructions The exam is closed book, closed notes. You may not use a calculator, cell phone, etc. For each of

More information

High Performance Programming Programming in C part 1

High Performance Programming Programming in C part 1 High Performance Programming Programming in C part 1 Anastasia Kruchinina Uppsala University, Sweden April 18, 2017 HPP 1 / 53 C is designed on a way to provide a full control of the computer. C is the

More information

C-LANGUAGE CURRICULAM

C-LANGUAGE CURRICULAM C-LANGUAGE CURRICULAM Duration: 2 Months. 1. Introducing C 1.1 History of C Origin Standardization C-Based Languages 1.2 Strengths and Weaknesses Of C Strengths Weaknesses Effective Use of C 2. C Fundamentals

More information

Arrays. Example: Run the below program, it will crash in Windows (TurboC Compiler)

Arrays. Example: Run the below program, it will crash in Windows (TurboC Compiler) 1 Arrays General Questions 1. What will happen if in a C program you assign a value to an array element whose subscript exceeds the size of array? A. The element will be set to 0. B. The compiler would

More information

UNIT-I Fundamental Notations

UNIT-I Fundamental Notations UNIT-I Fundamental Notations Introduction to Data Structure We know that data are simply values or set of values and information is the processed data. And actually the concept of data structure is much

More information

Memory, Arrays & Pointers

Memory, Arrays & Pointers 1 Memory, Arrays & Pointers Memory int main() { char c; int i,j; double x; c i j x 2 Arrays Defines a block of consecutive cells int main() { int i; int a[3]; i a[0] a[1] a[2] Arrays - the [ ] operator

More information

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples:

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples: 1 Programming in C Pointer Variable A variable that stores a memory address Allows C programs to simulate call-by-reference Allows a programmer to create and manipulate dynamic data structures Must be

More information

C: How to Program. Week /Mar/05

C: How to Program. Week /Mar/05 1 C: How to Program Week 2 2007/Mar/05 Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers

More information

ONE DIMENSIONAL ARRAYS

ONE DIMENSIONAL ARRAYS LECTURE 14 ONE DIMENSIONAL ARRAYS Array : An array is a fixed sized sequenced collection of related data items of same data type. In its simplest form an array can be used to represent a list of numbers

More information

Have examined process Creating program Have developed program Written in C Source code

Have examined process Creating program Have developed program Written in C Source code Preprocessing, Compiling, Assembling, and Linking Introduction In this lesson will examine Architecture of C program Introduce C preprocessor and preprocessor directives How to use preprocessor s directives

More information

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been

More information

Goals of this Lecture

Goals of this Lecture C Pointers Goals of this Lecture Help you learn about: Pointers and application Pointer variables Operators & relation to arrays 2 Pointer Variables The first step in understanding pointers is visualizing

More information

Unit IV & V Previous Papers 1 mark Answers

Unit IV & V Previous Papers 1 mark Answers 1 What is pointer to structure? Pointer to structure: Unit IV & V Previous Papers 1 mark Answers The beginning address of a structure can be accessed through the use of the address (&) operator If a variable

More information

Kurt Schmidt. October 30, 2018

Kurt Schmidt. October 30, 2018 to Structs Dept. of Computer Science, Drexel University October 30, 2018 Array Objectives to Structs Intended audience: Student who has working knowledge of Python To gain some experience with a statically-typed

More information

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Slide Set 3. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng

Slide Set 3. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng Slide Set 3 for ENCM 339 Fall 2017 Section 01 Steve Norman, PhD, PEng Electrical & Computer Engineering Schulich School of Engineering University of Calgary September 2017 ENCM 339 Fall 2017 Section 01

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Lecture Notes on Memory Layout

Lecture Notes on Memory Layout Lecture Notes on Memory Layout 15-122: Principles of Imperative Computation Frank Pfenning André Platzer Lecture 11 1 Introduction In order to understand how programs work, we can consider the functions,

More information

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #29 Arrays in C (Refer Slide Time: 00:08) This session will learn about arrays in C. Now, what is the word array

More information

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Arrays and Pointers. CSE 2031 Fall November 11, 2013 Arrays and Pointers CSE 2031 Fall 2013 November 11, 2013 1 Arrays l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. 2 Arrays: Example

More information

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

Chapter 1 & 2 Introduction to C Language

Chapter 1 & 2 Introduction to C Language 1 Chapter 1 & 2 Introduction to C Language Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 1 & 2 - Introduction to C Language 2 Outline 1.1 The History

More information

Class Information ANNOUCEMENTS

Class Information ANNOUCEMENTS Class Information ANNOUCEMENTS Third homework due TODAY at 11:59pm. Extension? First project has been posted, due Monday October 23, 11:59pm. Midterm exam: Friday, October 27, in class. Don t forget to

More information

Variables and Constants

Variables and Constants HOUR 3 Variables and Constants Programs need a way to store the data they use. Variables and constants offer various ways to work with numbers and other values. In this hour you learn: How to declare and

More information

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ... Why Pointers Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation. They provide support for dynamic data structures, such

More information

EL6483: Brief Overview of C Programming Language

EL6483: Brief Overview of C Programming Language EL6483: Brief Overview of C Programming Language EL6483 Spring 2016 EL6483 EL6483: Brief Overview of C Programming Language Spring 2016 1 / 30 Preprocessor macros, Syntax for comments Macro definitions

More information

C Language Programming

C Language Programming Experiment 2 C Language Programming During the infancy years of microprocessor based systems, programs were developed using assemblers and fused into the EPROMs. There used to be no mechanism to find what

More information

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University Fundamental Data Types CSE 130: Introduction to Programming in C Stony Brook University Program Organization in C The C System C consists of several parts: The C language The preprocessor The compiler

More information

KOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming

KOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 1 ARRAYS ~ VECTORS KOM3191 Object-Oriented Computer Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 2 What is an array? Arrays

More information

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ. C BOOTCAMP DAY 2 CS3600, Northeastern University Slides adapted from Anandha Gopalan s CS132 course at Univ. of Pittsburgh Pointers 2 Pointers Pointers are an address in memory Includes variable addresses,

More information

Chapter 1 Getting Started

Chapter 1 Getting Started Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different

More information

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows Unti 4: C Arrays Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type An array is used to store a collection of data, but it is often more useful

More information

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Quiz Start Time: 09:34 PM Time Left 82 sec(s) Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

edunepal_info

edunepal_info facebook.com/edunepal.info @ edunepal_info C interview questions (1 125) C interview questions are given with the answers in this website. We have given C interview questions faced by freshers and experienced

More information

EDIABAS BEST/2 LANGUAGE DESCRIPTION. VERSION 6b. Electronic Diagnostic Basic System EDIABAS - BEST/2 LANGUAGE DESCRIPTION

EDIABAS BEST/2 LANGUAGE DESCRIPTION. VERSION 6b. Electronic Diagnostic Basic System EDIABAS - BEST/2 LANGUAGE DESCRIPTION EDIABAS Electronic Diagnostic Basic System BEST/2 LANGUAGE DESCRIPTION VERSION 6b Copyright BMW AG, created by Softing AG BEST2SPC.DOC CONTENTS CONTENTS...2 1. INTRODUCTION TO BEST/2...5 2. TEXT CONVENTIONS...6

More information

CS201 Latest Solved MCQs

CS201 Latest Solved MCQs Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

C++ for Java Programmers

C++ for Java Programmers Basics all Finished! Everything we have covered so far: Lecture 5 Operators Variables Arrays Null Terminated Strings Structs Functions 1 2 45 mins of pure fun Introduction Today: Pointers Pointers Even

More information

Basic Types and Formatted I/O

Basic Types and Formatted I/O Basic Types and Formatted I/O C Variables Names (1) Variable Names Names may contain letters, digits and underscores The first character must be a letter or an underscore. the underscore can be used but

More information

ECE 250 / CS 250 Computer Architecture. C to Binary: Memory & Data Representations. Benjamin Lee

ECE 250 / CS 250 Computer Architecture. C to Binary: Memory & Data Representations. Benjamin Lee ECE 250 / CS 250 Computer Architecture C to Binary: Memory & Data Representations Benjamin Lee Slides based on those from Alvin Lebeck, Daniel Sorin, Andrew Hilton, Amir Roth, Gershon Kedem Administrivia

More information

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018 Pointer Basics Lecture 13 COP 3014 Spring 2018 March 28, 2018 What is a Pointer? A pointer is a variable that stores a memory address. Pointers are used to store the addresses of other variables or memory

More information

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014. Arrays Arrays and Pointers l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. EECS 2031 Fall 2014 November 11, 2013 1 2 Arrays: Example

More information

Work relative to other classes

Work relative to other classes Work relative to other classes 1 Hours/week on projects 2 C BOOTCAMP DAY 1 CS3600, Northeastern University Slides adapted from Anandha Gopalan s CS132 course at Univ. of Pittsburgh Overview C: A language

More information

C Structures & Dynamic Memory Management

C Structures & Dynamic Memory Management C Structures & Dynamic Memory Management Goals of this Lecture Help you learn about: Structures and unions Dynamic memory management Note: Will be covered in precepts as well We look at them in more detail

More information

Darshan Institute of Engineering & Technology for Diploma studies Unit 4

Darshan Institute of Engineering & Technology for Diploma studies Unit 4 Pointer A pointer is a variable that contains address or location of another variable. Pointer is a derived data type in C. Pointers contain memory address as their values, so they can also be used to

More information