C Programming Language

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
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
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:
Pointers Chapters 6+9 in ABC. abp 12 int a = 1, b = 2, *p; & - reference operator (address) * - dereference operator (value) p = &a; // *p is now 1 abp.
1 Arrays and Strings. 2 An array is a collection of variables of the same type that are referred to through a common name. It is a Data Structure which.
1 Chapter 9 Arrays and Pointers. 2  One-dimensional arrays  The Relationship between Arrays and Pointers  Pointer Arithmetic and Element Size  Passing.
Arrays, Pointers and Strings Chapter 6 in ABC. One Dimensional Arrays #defineN100 int a[N]; for ( i = 0; i< N; ++i ) sum += a[i]; space for a[0],...,
1 CS 201 Array Debzani Deb. 2 Having trouble linking math.h? Link with the following option gcc –lm –o test test.o.
1 Chapter 8 Functions, Pointers, and Storage Classes  Pointer  Pointers to void  Call-by-Reference  Basic Scope Rules  Storage Classes  Default Initialization.
1 Review of Chapter 6: The Fundamental Data Types.
C Programming Lecture 14 Arrays. What is an Array? b An array is a sequence of data items that are: all of the same typeall of the same type –a sequence.
Pointers CSE 2451 Rong Shi.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
C++ Lecture 3 Monday, 14 July Arrays, Pointers, and Strings l Use of array in C++, multi- dimensional array, array argument passing l Pointers l.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.
Arrays and Pointers1 Arrays of Arrays: We can have arrays of any type, even arrays whose elements are themselves arrays. With two bracket pairs, we obtain.
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.
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:
Arrays and Pointers.
Arrays, Strings, and Memory. Command Line Arguments #include int main(int argc, char *argv[]) { int i; printf("Arg# Contents\n"); for (i = 0; i < argc;
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
19-Feb-02 Sudeshna Sarkar, CSE, IIT Kharagpur1 Arrays, Pointers, Strings Lecture 18 19/2/2002.
Chapter 5 Pointers and Arrays Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 9.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
C Programming Lecture 15 Two Dimensional Arrays. Two-Dimensional Arrays b The C language allows arrays of any type, including arrays of arrays. With two.
1-d Arrays.
Stack and Heap Memory Stack resident variables include:
Computer Organization and Design Pointers, Arrays and Strings in C
Arrays An array is a grouping of elements of the same type that share a common base name Can have any number of elements in the array Individual elements.
Computer Programming BCT 1113
Lecture 7 Arrays 1. Concept of arrays Array and pointers
Command-Line Arguments
Module 2 Arrays and strings – example programs.
Programmazione I a.a. 2017/2018.
Arrays and Pointers CSE 2031 Fall September 2018.
Programming Languages and Paradigms
Lecture 6 C++ Programming
Pointers.
Programming and Data Structures
Instructor: Ioannis A. Vetsikas
7 Arrays.
Lecture 10 Arrays.
Pointers and Pointer-Based Strings
بنام خدا زبان برنامه نویسی C (21814( Lecture 11 Pointers
CS111 Computer Programming
Lecture 18 Arrays and Pointer Arithmetic
Pointers.
Programming with Pointers
Review of Arrays and Pointers
Pointers.
prepared by Senem Kumova Metin modified by İlker Korkmaz
Outline Defining and using Pointers Operations on pointers
Dynamic Memory Allocation (and Multi-Dimensional Arrays)
7 Arrays.
C++ Pointers and Strings
Exercise Arrays.
Arrays An array is a grouping of elements of the same type that share a common base name Can have any number of elements in the array Individual elements.
(PART 2) prepared by Senem Kumova Metin modified by İlker Korkmaz
Arrays, Pointers, and Strings
C++ Pointers and Strings
Pointers.
Presentation transcript:

C Programming Language Arrays, Pointers and Strings 2000 Instructor : Lee, Kyu-Woong email : leekw@mail.sangji.ac.kr voice : 033-730-0488

Arrays array declaration for use homogeneous data; e.g. grade1, grade2, .. declaration type identified[constant integral expression] expression : positive (size of array) subscrpt : from 0 to size -1 int a[size]; lowerbound = 0 upperboud = size -1 size = upperbound + 1 good programming style #define N 100 int a[N]; processing array element for (i=0; i<N; i++) sum += a[i];

Initialization array initialization external and static array storage class for automatic, external, or static not for register initialization float f[5] = {0.0, 1.0, 2.0 , 3.0, 4.0 } when ( # of initializer < # of array element ) remaining elements : zero ex) int a[100] = {0}; external and static array all elements to zero by default automatic array are not initialized by the system stating with "garbage values"

Initialization declaration without a size if it is initialized to a series of values, given the size of the number of initializers int a[] = { 2, 3, 5, 1} is equivalent to int a[4] = {2, 3, 5, 1} useful for charter string char s[]= "language" is taken by the system char s[] = {'l', 'a', 'n', 'g', 'u', 'a', 'g', 'e' , '\n'};

Subscipting a[expr] expr : integral expression( subscript or index) int a[N]; N : symbolic constant a[i] 0 <= i <= N-1 outside range : runtime error bracket pair, [ ] treated as operator () and [] highest prcedence and left to right associativity

Pointers simple variable pointer stored in a certain number of bytes at a particular memory location or address pointer are used to access memory and manipulate address if v is variable, then &v is the address & : unary operator ( inverse operator *) &(p+1) or &(20) : illegal pointer variable used to take addresses as values int *p; p =0 ; p = NULL; p = &i; p = (int *) 1776;

Pointers *p the value of the variable of which p is the address direct value of p is the memory location whereas the *p is the indirect value of p the value at the memory location stored in p direct value of P P p : yyyy xxxx int a=10; int *p; p = &a; printf("%o\n", &a); /* xxxx */ printf("%o\n", &p); /* yyyy */ printf("%o\n", p); /* xxxx */ printf("%d\n", *p); /* 10 */ indirect value of P *P a : xxxx 10 variable : adddress

Pointers int a=1, b=2, *p; p = &a; b= *p; /* is equivalent to b = a; */ 1 2 a b 1 2 a b 1 1 a b

Pointers note a pointer can be initialized in a declaration int i, *p = &i; initialization of p, not *p variable of p is type int * and initial value is &i declaration of i must occur before we take its address p contains an address or location *p the value of what is stored at this location conversions during assignment between different pointers are not allowed ( In traditional C, it may be allowed)

Expressions of Pointer declaration and initialization int i=3, j =5, *p = &i, *q = &j, *r; double x; expression equivalent expression value p == &i p == ( &i) 1 * * & p * ( * (&p)) 3 r = & x r = ( & x) illegal 7 * * p / * q + 7 (((7 * (*p))) / ( *q) + 7 11 * ( r =&j) *= * p (* (r = (&j) )) *= (*p) 15

Call-By-Reference call-by-value call-by-reference their values are copied to the corresponding function parameters the variables in the calling environment are not changed call-by-reference the variables used in parameter list in the calling environment are changed as the value of function addresses of variables must be passed as arguments pointers must be used in the paramenter list in the function definition

Call-By-Reference #include <stdio.h> void swap(int *, int *); int main(void) { int i=3, j=5; swap(&i,&j); printf("%d %d\n", i,j ); return 0; } void swap(int *p, int *q) int tmp; tmp = *p; *q = *p; *p = tmp; xxxx i = 3 yyyy j = 5 p = xxxx, q = yyyy *p = 3, *q = 5

Pointers and Arrays array name address or pointer value and pointers by itself constant pointer pointer variable different addresses as values array address or pointer that is fixed if a is array a[i] is equivalent to *(a+i) if p is pointer p[i] is equivalent to *(p+i) we can use array notation with pointers

Pointers and Array pointer arithmetic base address of array a : array , p : pointer a + i as its value the ith offset from the base address of array a ith element of the array p + i as its value the ith offset from the value(address) of p base address of array initail location in memory where the arrray is stored the address of the first element (index 0) of the array

Pointers and Arrays array a 300 a[0] #define N 100 int a[N], *p, sum =0; a[0] 304 a[1] 308 a[2] 684 p =a ; is equivalent to p =&a[0] p=a+1; is equivalent to p=&a[1] /* variation of summation of array a */ for ( p=a; p < &a[N] ; ++p) sum += *p; for(i=0; i < N; ++i) sum += *(a+i); p=a; sum += p[i]; a[96] 688 a[97] 692 a[98] 696 a[99] ★ note : illegal operation a =p; ++a; a += 2; &a; /* a is array name and constant pointer */

Pointers and Arrays ★ pointer arithmetic and element size int *p, *q, a[2]; p=a; q = p +1; printf( "%o\n", p); /* 35777775170 */ printf("%o\n", q); /* 35777775174 */ printf("%o\n", q-p); /* 1 ( because of pointer arithmetic) */ printf("%d\n", (int)q - (int)p); /* 4 */

Array as Function Arguments array as arguments a formal parameter that is declared as an array actually a pointer base address of the array is passed "call-by-value" array elements are not copied #include <stdio.h> main() { int a[10]={0,1,2,3,4,,6,7,8,9}; void func(int []); func(a); } void func(int x[]) /* or void func(int *x), or void func(int x[10]) */ { /* void func(int x[5]) numeric value : no meanig */ int i; for(i=0; i<10; i++) printf("%d\n", x[i]);

Bubble Sort ith iteration : void bubble(int a[], int n) find the ith smallest number i.e) find the smallest number in the list of a[i] ...a[n] void bubble(int a[], int n) { int i,j; void swap(int *, int *); for ( i=0; i < n-1; ++i) /* no need to find the largest element */ for (j=n-1 ; j>i; --j) /* the largest index : n-1 */ if ( a[j-1] > a[j] ) swap(&a[j-1], &a[j]); } n=8 i j

Program Report write a baseball game generating the 4 digits by using rand() function get the 4 digits from user's key input compare the user's number and random number if the value of ith digit is the same to the ith digit of random number , then "strike" is displayed if the value of ith digit is the same to the jth digit of random number , then "ball" is displayed until ( 4 strike or 40 times) continue game ? (y/n)

Dynamic Memory Allocation calloc() and malloc() function prototypes are in stdlib.h contiguous memory allocation : calloc() memeory allocation : malloc() to dynamically create space for arrays, structures and unions #include <stdio.h> main() { char *s; gets(s); printf(" string : %s\n, s); } /* no compile error, but run-time error */ s = malloc(10);

Dynamic Memory Allocation #include <stdio.h> #include <stdlib.h> main() { int *a, n ; ...... a = calloc(n, sizeof(int)); } use a as an integer array calloc two arguments size_t number of element size_t size of each element ( size_t : unsigned int) return success : points to the base of the array in memory fail : NULL initialized with all bits set to zero

Dynamic Memory Allocation malloc allocates a specified number of bytes of memory the initial value of the memory is inderterminate argument size_t size of memory to be allocated #include <stdio.h> main() { char *s,temp; gets(temp); s = malloc( strlen(temp ) + 1) ; strcpy(s, temp); printf(" string : %s\n, s); }

Strings strings one-dimesional arrays of type char terminated by the end-of-string sentinel \0 or null character string constant treated as a pointer ( base address of the string ) char *p = "abc"; printf( " %s %s \n", p p+1); /* abc bc is printed */ p is assigned the base address of "abc" p + 1 points to the letter b "abc" treated as a pointer "abc"[1] is equivalent to p + 1 *("abc" + 2)

String Handling Functions char *strcat( char *s1, const char *s2); int strcmp(const char *s1, const char *s2); char *strcpy(char *s1, const char *s2); unsigned strlen(const char *s); const : the character pointed to in memory should not be changed

String Handling Function char *strcat(char *s1, const char *s2) { register char *p = s1; while (*p) /* while ( *p != '\0') ++p; while ( *p++ = *s2++) ; return s1; }

Multidimensional Array arrays of any type including arrays of arrays a[n][m] the n array of m array n ×m elements base address : a[0][0] col 1 col 2 col 3 .... col m row 1 row 2 row 3 .... row n a[0][0] a[0][1] a[0][2] a[0][m] a[1][0] a[1][1] a[1][2] a[1][m] a[2][0] a[2][1] a[2][2] a[2][m] .................... a[n][0] a[n][1] a[n][2] a[n][m]

Multidimensional Arrays array elements are stored contiguously one after the other linear order row-major order example : address of a[i][j] base address of a + ( ( i × j ) + j) × sizeof( element ) base address of array a[3][5] = 100 address of element a[2][3] 100 +{ 2 × 5 + 3 } × sizeof(element) efficiency for (i=0; i<n; i++) for(j=0; j<m; j++) sum += a[i][j] for (j=0; j<m; j++) for(i=0; i<n; i++) sum += a[i][j] is more efficient than

Multidimensional Arrays numerous ways to access elements expressions equivalent to a[i][j] *(a[i] + j ) ( *(a+i) ) [j] * ( ( *(a+i)) + j ) * ( &a[0][0] + 5*i + j) three dimensional array int a[7][9][2];

Multidimensional Arrays initialization int a[2][3] = { 1,2,3,4,5,6}; if there are no inner braces then a[0][0], a[0][1], a[0][2] ... remaning elements : zero int a[2][3] = { { 1,2,3 }, { 4,5,6} } int a[][3] = { {1,2,3} , {4,5,6} } if the first bracket pair is empty the number of inner brace pairs all sizes except the first must be given explicitly

Multidimensional Arrays matrix multifly #define L 4 #define M 5 #define N 3 typedef double matrix_a[L][M] typedef double matrix_b[M][N] typedef double matrix_c[L][M] ..... void multiply(matrix_a a, matrix_b b, matrix_c c) { int i,j,k; for( i = 0; i < L; i ++) for (j =0; j<N; j++) { c[i][j] = 0.0; for ( k=0; k < M; k++) c[i][j] += a[i][k] * b[k][j] ; }

array of pointers array of pointers char *s[3]; s[0] "abcde\n" equivalnet to char * ( s[3] ); s[0] "abcde\n" s[1] "xyz\n" s[2] "test\n" swap(&s[1], & s[2]); swap(char **p, char **q) { char *tmp; tmp = *p; *p = *q; *q = tmp ; }

arguments to main() main function int argc : argument count char *argv[] : argument value #include <stdio.h> main(int argc, char *argv[]) { int i; for ( i=0; i<argc; i++) printf(" argument %d : %s\n", i, argv[i]); } %a.out test.c test.dat test.out argument 0 : a.out argument 1 : test.c argument 2 : test.dat argument 3 : test.out

Function as Arguments pointers to functions example can be passed as arguments example call : sum_square(sin,2,13) double sum_square(double f(double), int m, int n) { int k; double sum = 0.0; for ( k = m ; k < = n ; k++) sum += f(k) + f(k) ; return sum; }

Function as Arguments equivalent header note : double sum_square( double (* f)(double), int m int n) " f is a pointer th function that takes a single argument of type double and returns a double " note : double *f(double) : function f that takes an argument of type double and returns a pointer to double

Example #include <stdio.h> #define M 5 #define N 5 main() { int MAT[M][N] = { {0,1,2,3,4}, {10,11,12,13,14}, {20,21,22,23,24}, {30,31,32,33,34}, {40,41,42,43,44} }; int i, j; for(i=0; i<M; i++) for(j=0; j<N; j++) printf("MAT[%d][%d]: %3d\t", i, j, MAT[i][j]); printf("\n"); }