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:

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

C Language.
Lectures 10 & 11.
Programming and Data Structure
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Lecture 20 Arrays and Strings
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.
Pointers in C Rohit Khokher
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
Kernighan/Ritchie: Kelley/Pohl:
POINTER Prepared by MMD, Edited by MSY1.  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference.
Chapter 10.
Memory Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
Pointers: Part I. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program.
Chapter 9: Arrays and Strings
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Introduction of Arrays. Arrays Array form an important part of almost all programming language. It provides a powerful feature and can be used as such.
Chapter 8 Arrays and Strings
Pointers Applications
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
Functions in C. Function Terminology Identifier scope Function declaration, definition, and use Parameters and arguments Parameter order, number, and.
Strings in C. Strings are Character Arrays Strings in C are simply arrays of characters. – Example:char s [10]; This is a ten (10) element array that.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
1 Arrays Chapter 13 Especially read 13.1 – 13.2 Text introduces vectors, which we will not cover, in 13.3.
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
Chapter 8 Arrays and Strings
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
(continue) © by Pearson Education, Inc. All Rights Reserved.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Spring 2005, Gülcihan Özdemir Dağ Lecture 7, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 7 Outline 7. 1.
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
C Programming Day 4. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 More on Pointers Constant Pointers Two ways to.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
1 Pointers to structs. 2 A pointer to a struct is used in the same way as a pointer to a simple type, such as an int. Pointers to structs were introduced.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Spring 2005, Gülcihan Özdemir Dağ Lecture 8, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 8 Outline 8.1 Declaring.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
Pointers *, &, array similarities, functions, sizeof.
© Oxford University Press All rights reserved. CHAPTER 7 POINTERS.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Computer And Programming Array and Pointer. Array provides a means to allocating and accessing memory. Pointers, on the other hand, provides a way to.
FUNCTIONS. Midterm questions (1-10) review 1. Every line in a C program should end with a semicolon. 2. In C language lowercase letters are significant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
© Janice Regan, CMPT 128, January CMPT 128: Introduction to Computing Science for Engineering Students Introduction to Arrays.
Chapter 16 Pointers and Arrays Pointers and Arrays We've seen examples of both of these in our LC-3 programs; now we'll see them in C. Pointer Address.
1 Arrays and Pointers The name of an array is a pointer constant to the first element. Because the array’s name is a pointer constant, its value cannot.
1 ENERGY 211 / CME 211 Lecture 4 September 29, 2008.
Arrays. C++ Style Data Structures: Arrays(1) An ordered set (sequence) with a fixed number of elements, all of the same type, where the basic operation.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
Arrays An array is a sequence of objects all of which have the same type. The objects are called the elements of the array and are numbered consecutively.
Java Programming Language Lecture27- An Introduction.
Windows Programming Lecture 03. Pointers and Arrays.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Objectives You should be able to describe: One-Dimensional Arrays
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
C Programming Tutorial – Part I
Arrays in C.
Lecture 6 C++ Programming
Data Structures and Algorithms Introduction to Pointers
Presentation transcript:

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}; C Programming Language 1-dimensional arrays 1 Prepared by Dr.Konstantin Degtiarev, a presence of [10] means that both declared variables are arrays with 10 elements (all elements are of the type int) a presence of [10] means that both declared variables are arrays with 10 elements (all elements are of the type int) typedef is used to assign a new name temp to existing type int; typedef is used to assign a new name temp to existing type int; the initialization list is too short, but still all elements are initialized

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"}; C Programming Language 1-dimensional arrays 2 Prepared by Dr.Konstantin Degtiarev, 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 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… two forms of strings initialization – the second one seems more natural… 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 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.

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"; C Programming Language 1-dimensional arrays 3 Prepared by Dr.Konstantin Degtiarev,

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 Example 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) */ C Programming Language 1-dimensional arrays 4 Prepared by Dr.Konstantin Degtiarev, 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 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 ! ! example of pointer arithmetic…

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 C Programming Language 1-dimensional arrays 5 Prepared by Dr.Konstantin Degtiarev,

Pointer arithmetic [4] Example 29A 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); C Programming Language 1-dimensional arrays 6 Prepared by Dr.Konstantin Degtiarev,

Operations on pointers [1] Example 30 Example 30 #include 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; } C Programming Language 1-dimensional arrays 7 Prepared by Dr.Konstantin Degtiarev, the function memcpy( ) copies count symbols from the array which is pointed to by source to the array to which dest pointing to 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 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 sizeof(int) gives the result 2 (MS-DOS) or 4 (UNIX/Windows) pay attention to the usage of sizeof(b) pay attention to the usage of sizeof(b)

4 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. 4 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 C Programming Language 2-dimensional arrays 1 Prepared by Dr.Konstantin Degtiarev,

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}; …. int src [5][7]; printf(“array requires in the memory %d bytes storage”, sizeof( src )); ….. C Programming Language 2-dimensional arrays 2 Prepared by Dr.Konstantin Degtiarev, 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) compiler complains: “size of type is unknown or zero" (error message) ! ! The number of bytes = 5*7*2(4) = 70(140)

Examples 4 As in the case of one-dimensional arrays, the access to elements of two- dimensional arrays is possible by means of (1) indexing and/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]) 4 Pointers (and dereference operators) are always used by compiler to get access to the elements of arrays indexing pointer arithmetic/dereference 4 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) C Programming Language 2-dimensional arrays 3 Prepared by Dr.Konstantin Degtiarev, ! !

Examples 4 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 pointer arr which points to array of 5 integers 4 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 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) C Programming Language Arrays and pointers 1 Prepared by Dr.Konstantin Degtiarev, ! !

Examples. Qualifier const Example 31 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] */ ……… 4 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 */ } C Programming Language Arrays and pointers 2 Prepared by Dr.Konstantin Degtiarev, expression in the header of if statement can be rewritten as follows: if(!gets(arr[2]) …… 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( ) integer value 0 (zero) is compatible with pointers ! See the following examples (using of qualifier const)

Examples. Qualifier const 4 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 C Programming Language Arrays and pointers 3 Prepared by Dr.Konstantin Degtiarev, Both forms are valid (const char and char const) ERRORS are highlighted…

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 4 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 C Programming Language Arrays and pointers 4 Prepared by Dr.Konstantin Degtiarev, the string “first choice” remains protected (read-only), if it is accessed through the pointer pt … 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

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…” 4 Differences between arrays and pointers: C Programming Language Arrays and pointers 5 Prepared by Dr.Konstantin Degtiarev, P.van den Linden. Expert C programming. Deep C secrets