Download presentation
Presentation is loading. Please wait.
1
C Programming Language
Arrays, Pointers and Strings 2000 Instructor : Lee, Kyu-Woong voice :
2
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];
3
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"
4
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'};
5
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
6
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;
7
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
8
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
9
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)
10
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) * * & p * ( * (&p)) r = & x r = ( & x) illegal 7 * * p / * q + 7 (((7 * (*p))) / ( *q) * ( r =&j) *= * p (* (r = (&j) )) *= (*p)
11
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
12
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
13
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
14
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
15
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 */
16
Pointers and Arrays ★ pointer arithmetic and element size
int *p, *q, a[2]; p=a; q = p +1; printf( "%o\n", p); /* */ printf("%o\n", q); /* */ printf("%o\n", q-p); /* 1 ( because of pointer arithmetic) */ printf("%d\n", (int)q - (int)p); /* 4 */
17
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]);
18
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
19
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)
20
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);
21
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
22
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); }
23
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)
24
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
25
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; }
26
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 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]
27
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 × } × 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
28
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];
29
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
30
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] ; }
31
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 ; }
32
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
33
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; }
34
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
35
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"); }
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.