1 / 15

C Programming Language 1-dimensional arrays 1

Prepared by Dr.Konstantin Degtiarev, 12.05.2000. C Programming Language 1-dimensional arrays 1. General comments [1] array is a fixed sized group in which the elements are of the same type The general form of array's definition is as follows:

tameka
Télécharger la présentation

C Programming Language 1-dimensional arrays 1

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Prepared by Dr.Konstantin Degtiarev, 12.05.2000 C Programming Language 1-dimensional arrays1 General comments [1] • array is a fixed sized group in which the elements are of the same type • The general form of array's definition is as follows: type name_of_array[constant_expression] = {initialization_list}; where constant_expression (if present) specifies a size of array (the number of elements in the array) example A:float my_array[10]; example B:typedef int temp[10]; temp my_array1, my_array2; example C:int arr[4] = {1,10,20,30}; example D:int arr[4] = {1,10}; typedef is used to assign a new name temp to existing type int; a presence of [10] means that both declared variables are arrays with 10 elements (all elements are of the type int) the initialization list is too short, but still all elements are initialized

  2. Prepared by Dr.Konstantin Degtiarev, 12.05.2000 C Programming Language 1-dimensional arrays2 Examples example E:int arr[ ] = {1,10,20,30,40}; example F:int arr[4] = {1,10,20,30,40}; example G:char arr[8] = {'E','x','a','m','p','l','e','\0'}; example H:char arr[8] = "Example"; example I:char *arr[ ]= {"first", "second", "third"}; array arr[ ] is unsized, but according to the initialization list, C/C++ compiler creates an array (memory storage) of the size which is enough to hold all initial values present compiler complains: "too many initializers" (error message) two forms of strings initialization – the second one seems more natural… It should be noted that indices of array's elements start with zero (0), so that the index of the element specifies NOT its order number, but the offset from the beginning of the array. array arr has 3 elements, and each element is a pointer to corresponding string; for example, the following call printf ("%s",arr[2]); results in displaying the string third on the screen of monitor

  3. Prepared by Dr.Konstantin Degtiarev, 12.05.2000 C Programming Language 1-dimensional arrays3 Pointer arithmetic [1] • In C/C++ arrays are implemented by means of pointers: the name of array is a constant pointer which keeps the address of the first element of the array: name_of_array == &name_of_array == &name_of_array[0]  • Array subscripting a[i] in C is an example of the pointer arithmetic: a[i] == *(a + i ) == *(i + a) == i[a] • Compiler allocates array in sequential memory cells, and in order to get access to any element of the array, we have to know the basic address (where the storage of the whole structure starts?). • The formula for calculating the number of elements in the array arr: n = (sizeof (arr)) / sizeof arr[0] (as an operand for the operator sizeof array's arr[ ] name "recollects" that it stands for the array) • For example, if array is initialized as char my[ ] = "Small example\n";

  4. Prepared by Dr.Konstantin Degtiarev, 12.05.2000 C Programming Language 1-dimensional arrays4 Pointer arithmetic [2] …then the statement printf ("\"%s\" has a %d bytes storage", my, sizeof my); produces the following output: "Small example " has a 15 bytes storage Example 29 ...... int *p, arr[5] = {11,12,13}; p = arr+2; /* pointer p points to the third element (arr[2] ) of the array */ printf("the address of the element arr[1] is %p\n", p-1); printf("the value of arr[1] is %d", p[-1] ); ........ /* p[-1] is equivalent to *(p-1) */ example of pointer arithmetic… after assignment p = arr+2; is done, the element 12 of the array can be reached either by means of array's name indexing ( arr[1] ) or through pointer p indexing ( p[-1] ) - both cases are examples of pointer arithmetic ! at the same time we should not forget that ARRAYS and POINTERS are NOT EQUIVALENT

  5. Prepared by Dr.Konstantin Degtiarev, 12.05.2000 C Programming Language1-dimensional arrays5 Pointer arithmetic [3] • Suppose the following declaration part: double a[20], b[20]; (both arrays are initialized in the body of hypothetical program). What can we say about the statement: a = b; (in many programming languages it corresponds to element-by-element copying) ? A: in C/C++ this statement causes ERROR, because the name of array is a constant pointer: a is equivalent to &a[0], whereas b - to &b[0]. Thus, the statement a = b; is an attempt to change a contents of constant pointer a • It is important to remember:While doing pointer arithmetic, you always have to "control" the bounds of the array and to use (reference) only elements within these bounds. C compiler does NOT deal with bounds checking, so it becomes again a responsibility of a programmer. It is also worth mentioning that pointer arithmetic used to access arrays is faster than arrays indexing

  6. Prepared by Dr.Konstantin Degtiarev, 12.05.2000 C Programming Language1-dimensional arrays6 Pointer arithmetic [4] Example 29A ...... int a[ ] = {10, 15, 4, 25, 3, -4 }; /* array with 6 elements */ int *p = &a[2]; /* pointer p gets the address of the third element of the array a[ ] */   What are the results of the expressions given below (they are not dependent)? *(p+1) p[-1] p-a a[*p++] *(a+a[2] ) Please, provide a detailed explanation for each your answer • C language allows arrays of almost any types - in the case of two-dimensional array we can speak about array with the elements which are one-dimensional arrays • The prototype of the function memcpy( ) looks as follows: void *memcpy (void *dest, const void *source, size_t count);

  7. Prepared by Dr.Konstantin Degtiarev, 12.05.2000 C Programming Language1-dimensional arrays7 Operations on pointers [1] Example 30 #include<string.h> #include<stdio.h> int main(void) { char *src = "Hello, World..."; char *dest; int a[10] = {1,2,3,4,5,6,7,8}; int b[8]; short i; memcpy(dest, src, 12); dest = dest + '\0'; printf("the result is %s", dest); memcpy(b, a, 8*sizeof(int)); for (i=0; i <= (sizeof(b) / sizeof(b[0] )-1; i++) printf("%d\t", b[i] ); return 0; } the function memcpy( ) copies count symbols from the array which is pointed to by source to the array to which dest pointing to as a result of the statement dest = dest + ‘\0’; nul character is concatenated at the end to the sequence of 12 characters pointed to by the pointer dest pay attention to the usage of sizeof(b) sizeof(int) gives the result 2 (MS-DOS) or 4 (UNIX/Windows)

  8. Prepared by Dr.Konstantin Degtiarev, 12.05.2000 C Programming Language2-dimensional arrays1 • According to the declaration: int arr[2][3];/* variable with a name arr is two-dimensional array */ a majority of compilers store two-dimensional array in the memory in a row-major order, i.e. • Expression for the location of arbitrary array's element a[i][j] in terms of memory address where array starts brings us a notion of storage mapping function (SMF) - it "maps" a logical model of two-dimensional array (matrix) onto its physical allocation in computer's memory a[i][j] is equivalent to(*(arr + i ))[j] which, in its turn, is equivalent to* ((*(arr + i )) + j ) which is equivalent to *( &a[0][0] + m*i + j ) , where m is the number of columns in the matrix

  9. Prepared by Dr.Konstantin Degtiarev, 16.05.2000 C Programming Language2-dimensional arrays2 1 10 20 30 40 0 Examples example A:int arr[2][3] = {1,10,20,30,40}; example B:int arr[2][3] = {{1,10},{20,30,40}}; example C:int arr[2][3] = {{1},20,30,40}}; example D:int arr[ ][3] = {1,10,20,30,40}; example E:int arr[2][ ] = {1,10,20,30,40}; …. intsrc[5][7]; printf(“array requires in the memory %d bytes storage”, sizeof(src)); ….. 1 10 0 20 30 40 1 00 20 30 40 EXAMPLE D:the number of rows in the matrix arr is calculated automatically “through” the number of columns – from the beginning of the list elements are grouped by 3… compiler complains: “size of type is unknown or zero" (error message) The number of bytes = 5*7*2(4) = 70(140) !

  10. Prepared by Dr.Konstantin Degtiarev, 16.05.2000 C Programming Language 2-dimensional arrays3 Examples • As in the case of one-dimensional arrays, the access to elements of two-dimensional arrays is possible by means of (1) indexingand/or (2) pointer arithmetic • Consider the following declaration part: double arr1[3][5]; What can we say about the value of the expression: arr1+1 (example of pointer arithmetic – the current value of arr1 is incremented by 1) ? A:the expression has a value: arr1+sizeof(double)*5 (the address of the second row of the matrix arr1[3][5]) • Pointers (and dereference operators) are always used by compiler to get access to the elements of arrays • In the expressions You can always combine both access forms (indexing and pointer arithmetic/dereference), i.e. indexing form arr1[2][3](see the declaration above) is equivalent to pointer/dereference form *((*(arr1+2))+3) or *(arr1[2]+3) !

  11. Prepared by Dr.Konstantin Degtiarev, 16.05.2000 C Programming LanguageArrays and pointers1 Examples • Consider two declarations: int *arr[5]; and int (*arr)[5]; What is the difference between them? A:the first declaration states that arr is an array with 5 elements which are pointers to int, whereas the second one stands for pointerarr which points to array of 5 integers • The following declares an array of 10 strings (each string may consist of 39 characters as a maximum): char arr[10][40]; In order to fill strings (space allocated for them) with characters, we can use function gets( ) – its prototype char *gets(char * str); is specified in stdio.h header file: gets(arr[2]); is equivalent to gets(&arr[2][0]); (when <Enter> key is pressed, function gets( ) automatically converts its code to termination (nul) character ‘\0’; if the input is successful, then gets( ) returns str(see the prototype) , otherwise NULL is returned) !

  12. Prepared by Dr.Konstantin Degtiarev, 26.05.2000 C Programming LanguageArrays and pointers2 Examples. Qualifier const Example 31 ……… char arr[10][40]; printf(“Enter the third string: “); if(gets(arr[2]) == NULL) { printf(“There are problems with input string…”); exit(EXIT_FAILURE); } puts(arr[2]); /* outputs string pointed to by arr[2] */ ……… • Simplified implementation of the standard library function puts( ) can be thought to be as follows: int puts(const char *str) { while(*str) putchar(*str++); return 1; /* integer value is returned */ } integer value 0 (zero) is compatible with pointers ! expression in the header of if statement can be rewritten as follows: if(!gets(arr[2]) …… keyword const (qualifier) in the header of the function puts( ) tells the compiler that any values str points to will not be changed by the function puts( ) See the following examples (using of qualifierconst)

  13. Prepared by Dr.Konstantin Degtiarev, 26.05.2000 C Programming LanguageArrays and pointers3 Examples. Qualifier const • Qualifier const is a good “instrument” of protecting objects pointers point to when the latter are passed as arguments to functions example A:example B:example C: const char * pt1; char * const pt1; const char * const pt1; char const * pt2; *pt1 = ‘A’; char ch; char ch; pt1 += 4; ch = *pt1; ch = *pt1; *pt1 = ‘A’; *pt2 = ch; pt1 += 2; • A definition char * pt = “first choice”; allocates space for both pointer (pt) and string literal (“first choice”), and according to the requirements of Both forms are valid (const char and char const) ERRORS are highlighted…

  14. Prepared by Dr.Konstantin Degtiarev, 26.05.2000 C Programming LanguageArrays and pointers4 ANSI C, string used for initialization of pointer is read-only, i.e. printf(“the character is %c\n”, pt[4]); is possible (reading of string literal through pointer pt), but pt[4]=‘z’; is an attempt of writing which is not officially allowed in such situation • Consider the following fragment of the program: ……… const char * pt = “first choice”; char * pt2 = NULL; /* pointer pt2 is initialized */ int i=0; pt2=(char *)pt; /* in C it is possible not to use casting here */ while (*pt2 != ‘ ‘) { *(pt2+i++)=(char)(97+i); pt2++; } ……… “Array names in expressions “decay” into pointers. It simplifies things the string “first choice” remains protected (read-only), if it is accessed through the pointer pt … …but by means of any other pointer (e.g. pt2) which “knows” the address of this string literal, modification of “first choice” becomes possible P.van den Linden. Expert C programming. Deep C secrets, Prentice-Hall PTR, 1994

  15. Prepared by Dr.Konstantin Degtiarev, 26.05.2000 C Programming Language Arrays and pointers5 to treat arrays as pointers. We don’t need a complicated mechanism to treat them as a composite object, or suffer the inefficiency of copying everything when passing them to a function. But don’t make the mistake of thinking arrays and pointers are always equivalent…” • Differences between arrays and pointers: P.van den Linden. Expert C programming. Deep C secrets

More Related