2012年11月25日 星期日

Array and pointer – two key techniques in C program



In the CSCI1110, the topics “array” and “pointer” were taught in chapter 8 - 10. They are two of the key techniques used in writing C program. Now let me summarize what I have learnt from chapter 8 - 10.

Part 1

1.1 Contents of the lectures

In chapter 8-10, I have learnt some fundamental concepts about array and pointer. What are array and pointer? Arrays are data structures consisting of related data items of the same type. An array is a group of contiguous memory locations that all have the same type. To refer to a particular location or element in the array, we specify the array’s name and the position number of the particular element in the array; Pointers are variables whose values are memory addresses. A pointer contains an address of a variable that contains a specific value. A variable name directly references a value, and a pointer indirectly references a value. These two techniques make the design of the program easier since these techniques provide many of the capabilities programmer needs. Therefore, it is very important for a good programmer to acquire a good skill of using array and pointer. In chapter 8-10, the knowledge of array and pointer I had learnt include (1) defining and initializing arrays , (2) passing arrays to functions, (3) defining and initializing pointer variable(4) relationship between pointers and arrays.

(1)   Defining and initializing arrays :

  • Arrays occupy space in memory. We specify the type of each element and the number of elements in the array so that the computer may reserve the appropriate amount of memory.

  • An array of type char can be used to store a character string.

  • Type size_t represents an unsigned integral type. This type is recommended for any variable that represents an array’s size or an array’s subscripts. The header <stddef.h> defines size_t and is often included by other headers (such as <stdio.h>).

  • The element of an array can be initialized when the array is defined by following the definition with an equals sign and braces, {}, containing a comma-separated list of initializers. If there are fewer initializers than elements in the array, the remaining elements are initialized to zero.
  • If the array size is omitted from a definition with an initializer list, the number of elements in the array will be the number of elements in initializer list.





(2)    Passing arrays to functions:

  • To pass an array argument to a function, specify the name of the array without any brackets.
  • Unlike char arrays that contain strings, other array types do not have a special terminator. For this reason, the size of an array is passed to a function, so that the function can process the proper number of elements.
  • C automatically passes arrays to functions by reference – the called functions can be modified the element values in the caller’s original arrays. The name of the array evaluates to the address of the first element of the array. Because the starting address of the array is passed, the called function knows precisely where the array is stored. Therefore, when the called function modifiers array elements in its function body, it’s modifying the actual elements of the array in their original memory locations.


(3)   Defining and initializing pointer variable :

  • A pointer contains an address of another variable that contains a value. In this sense, a variable name directly references a value, and pointer indirectly references a value.
  • Referencing a value through a pointer is called indirection.
  • Pointers can be defined to point to objects of any type.
  • Pointers should be initialized either when they are defined or in an assignment statement. A pointer may be initialized to Null, 0 or an address. A pointer with the value NULL points to nothing. Initializing a pointer to 0 is equivalent to initializing a pointer to NULL, but NULL is preferred. The value 0 is the only integer value that cab be assigned directly to a pointer variable.



(4) Relationship between pointers and arrays

  • Arrays and pointers are intimately related in C and often may be used interchangeably.
  • An array name can be thought of as a constant pointer.
  • Pointers can be used to do any operation involving array subscripting.
  • When a pointer points to the beginning of an array, adding an offset to the pointer indicates which element of the arrays can. This is referred to as pointer/subscript notation.
  • An array name can be treated as a pointer and used in pointer and used in pointer arithmetic expressions that do not attempt to modify the address of the pointer.
  • Pointers can be subscripted exactly as arras can. This is referred to as pointer/subscript notation.
  • A parameter of type const char* typically represents a constant string.




More about arrays and pointer :


1.2 Learning Process:

In order to understand the principle of array and pointer and acquire the techniques of using them, I use different methods to let myself to understand the principle and uses of the techniques during the learning process.

(1)   To understand the principle of array in the view of box and cabinet relationship

For ordinary value, it is like a box for storing one value.

However, for array, it is like a cabinet containing many drawers. Each drawer stores one value. We can refer to each drawer as 1st drawer, 2nd drawer, 3rd drawer, etc.


(2) To understand the principle of pointer in form of graphical representation.


The above figure shows the representation of the pointer in memory, assuming that integer variable y is stored at location 1000, and pointer variable yPtr is stored at location 2000. Pointer variable yPtr stores the address of variable y ans has a value of 1000.

(3)  Record the common programming error in using array and pointer.

Since the use of array and pointer is complex, we may make some programming errors easily in using them. In order to acquire the techniques of using these two techniques accurately without mistakes or errors, I recorded the common programming error in using array and pointer and some error-prevention skills during the learning process.
  • Forgetting to initialize the elements of an array.
  • Providing more initializers in an array initializer list than there are elements in the array is a syntax error.
  • Assigning a value to a symbolic constant in an executable statement is a syntax error. A symbolic constant is not a variable. The compiler does not reserve space for symbolic constants as it does for variables that hold values at execution time.

  • Referring to an element outside the array bounds.

  • The asterisk (*) notation used to declare pointer variables does not distribute to all variable names in a declaration. Each pointer must be declared with the * prefixed to the name; e.g. if you wish to declare xPtr and yPtr as int pointers, use int* xPtr, *yPtr; .

  • Initializer pointers to prevent unexpected results.

  • Dereferencing a pointer that has not been properly initialized or that has nor been assigned to a point toa specific location in memory is an error.

  • Attempting to modify an array name with pointer arithmetic is a compilation error.

Part 2

2.1 A interesting topic in the lesson – application of arrays

A brief description about the math library function in C program :

Arrays in C can have many important computing applications. In the lecture, the applications below are introduced.

First, it can be used in sorting. Because of the way the successive comparsions are made, a large value may move down the array many positions on a single pass, but a small value may move up only one position.

Second, it can be used in searching. It is a process of finding a particular element of an array. The linear search compare each element of the array with the search key. Because the array is not in any particular order, it’s just as likely that the value will be found in the first element as in the last. On average, therefore, the search key will be compared with half the elements of the array.

Third, arrays in C can have multiple subscripts. A common use of multiple-subscripted arrays, which the C standard refers to as multidimensional arrays, is to represent tables of values consisting of information arranged in rows and columns.

2.2 My opinion, commends, ideas, and further information about application of array

I think the application of arrays is very useful and important in our real life.It can be used for solving mathematics problem and writing different program.

For example , a two-dimensional array ,which have two subscripts (row and column) , can be used to create a 2D board. For example , we can write a connect four game by C program in an easy way because we can use a two-dimensional array to create a game board.



Apart from it, another application of arrays that had not mentioned in the lecture is computing mean, median and mode using arrays.

For example, by the following C program using array :

#include<stdio.h>
#include<conio.h>
main()
{
int marks[100];
int i,n,sum,average;
printf("enter the number of students");
scanf("%d",&n);
printf("enter %d student's marks",n);
sum=0;
for(i=0;i<n;i++)
{
scanf("%d",&marks[i]);
sum=sum+marks[i];
}
average=sum/n;
printf("the sum of the marks of %d studens is %d\n",n,sum);
printf("the average of %d students is %d\n",n,average);
getch();
}

We can find out the average of marks of studens easily.

From these examples, we can see that arrays in C program is a very useful tool for program design. It can help engineer to solve difficult and complex mathematics or engineering problem in the real applications. In fact, arrays have a wide range of application such as ,to implement mathematical vectors and matrices, implement other data structures, determine partial or complete control flow in program. As a engineering student, I must acquire the techniques of using arrays for solving engineering problems.

More about application of array:


I think writing what I had learnt from the lesson in the blog is a good learning method. It not only reminds me what I had learnt but also helps me to revise for the examination. In the coming lecture, I will learn more advanced knowledge about C program. I will keep to write down my learning from the class in this blog. Hopefully, it can acquire a good skill of writing C program at the end of this semester and become a professional programer one day.

沒有留言:

張貼留言