8 주 강의 Arrays, Pointers, and Strings. One dimensional array int grad0, grad1, grad2;  int grad[3]; int a[size]; /* a[0], …, a[size-1] #define N 100 int.

Slides:



Advertisements
Similar presentations
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Advertisements

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
Programming in C Pointers and Arrays, malloc( ). 7/28/092 Dynamic memory In Java, objects are created on the heap using reference variables and the new.
More Pointers Write a program that: –Calls a function to input an integer value –The above function calls another function that will double the input value.
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:
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
CSSE 332 Functions, Pointers in C. 2 Functions - why and how ? If a problem is large If a problem is large Modularization – easier to: Modularization.
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.
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],...,
What does this program do ? #include int main(int argc, char* argv[]) { int i; printf("%d arguments\n", argc); for(i = 0; i < argc; i++) printf(" %d: %s\n",
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
CS 201 String Debzani Deb.
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 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic.
Pointers Applications
1 Review of Chapter 6: The Fundamental Data Types.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
CPT: Arrays of Pointers/ Computer Programming Techniques Semester 1, 1998 Objectives of these slides: –to illustrate the use of arrays.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
0 Chap. 5 Pointers and Arrays 5.3Pointers and Arrays 5.4Address Arithmetic 5.5Character Pointers and Functions 5.6Pointer Arrays; Pointers to Pointers.
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.
1 Chapter 8 Arrays Pointers Strings ** * *. One-dimensional arrays An array stores a set of data of the same type. Note indexing of elements always starts.
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.
Functions & Pointers in C Jordan Erenrich
+ Dynamic memory allocation. + Introduction We often face situations in programming where the data is dynamics in nature. Consider a list of customers.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
More Pointers and Arrays Kernighan/Ritchie: Kelley/Pohl: Chapter 5 Chapter 6.
Arrays and Pointers.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 5.
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;
Pointers1 WHAT IS A POINTER? Simply stated, a pointer is an address. A running program consists of three parts: execution stack, code, and data. They are.
Today’s Material Strings Definition Representation Initialization
Multi-dimensional Arrays and other Array Oddities Rudra Dutta CSC Spring 2007, Section 001.
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
1 Dynamic Memory Allocation. 2 In everything we have done so far, our variables have been declared at compile time. In these slides, we will see how to.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
ADVANCED POINTERS. Overview Review on pointers and arrays Common troubles with pointers Multidimensional arrays Pointers as function arguments Functions.
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.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 9.
1 Memory, Arrays & Pointers. Memory 2 int main() { char c; int i,j; double x; cijx.
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.
Pointers and Dynamic Arrays
Characters and Strings
Pointers.
Pointers.
C Programming Language
Lecture 10 Arrays.
Lecture 18 Arrays and Pointer Arithmetic
Pointers.
Pointers.
prepared by Senem Kumova Metin modified by İlker Korkmaz
Outline Defining and using Pointers Operations on pointers
(PART 2) prepared by Senem Kumova Metin modified by İlker Korkmaz
Arrays, Pointers, and Strings
Dynamic Memory – A Review
Pointers.
Presentation transcript:

8 주 강의 Arrays, Pointers, and Strings

One dimensional array int grad0, grad1, grad2;  int grad[3]; int a[size]; /* a[0], …, a[size-1] #define N 100 int a[N]; /* a[0].. a[99] is allocated */ for(i=1; i<100; ++i) sum += a[i];

Initialization float f[5]={0.0, 1.0, 2.0, 3.0, 4.0}; int a[100]={0}; /* all elements to 0 */ int a[]={2,3,5,-7}; /* int a[4] … */ char s[] = “ abc ” ; /*  char s[] = { ‘ a ’, ‘ b ’, ‘ c ’, ‘ \0 ’ } */

Pointers &v 는 변수 v 의 location( 주소 ) int *p ::: declares p to be type pointer to int p=0;  p=NULL; p=&i; p=(int *) 1776 /* an absolute address */

Pointer 예 int a, b, *p; a=1; b=2; p=&a;

Pointer 에 의한 접근의 결과 Declarations and initializations int i=3, j=5, *p=&i, *q=&j, *r; double x; ExpressionEquivalent expressionValue p == & ip == (& i)1 * * & p* ( * ( & p))3 r = & xr = (& x)/* illegal */ 7 * * p / * q + 7(((7 * (* p))) / (* p)) * (r = & j) *= * p(* (r = (& j))) *= (* p)15

Legality of opertions Declarations int float void * p; * q; * v; Legal assignmentsIllegal assignments p = 0;p = 1; p = (int *) 1;v = 1; p = v = q;p = q; p = (int *) q;

주의할 점 7 * * p / * q + 7 ??? 7 * * p /* q +7 --trouble making &3 /* illegal */ &(k+3) /* illegal */ register v; &v /* illegal */ &a[0], &a[i+j+3] /* legal */ int a[3]; &a ?????

Call by reference (address) To change the values of variables in the calling environment Simulating the effect of call by reference by pointers

예 void swap(int *p, int *q) { int tmp; tmp = *p; *p = *q; *q = tmp } int i=3, j=5; swap(&i, &j);

The simulation of call by reference Declaring a function parameter to be a pointer Using the de-referenced pointer in the function body Passing an address as an argument when the function is called

The relationship between arrays and pointers An array name itself is an address, or pointer value, and pointers as well as arrays, can be subscripted a[i]  *(a+i) #define N 100 int a[N], I, *p, sum=0;  p=a;  p=&a[0];  p=a+1  p=&a[1];

계속 for (p=a; p < &a[N]; ++p) sum += *p;  for(i = 0; i < N; ++i) sum += *(a + i);  p=a; for (i=0; i < N; ++i) sum += p[i];

Pointer 연산 int *a; short *b; float *c; double *d; a+1  주소 4 증가 b+1  주소 2 증가 c+1  주소 4 증가 d+1  주소 8 증가

Arrays as function arguments double sum(double a[], int n) { int i; double sum = 0.0; for (i = 0; i < n; ++i) sum+=a[i]; return sum; }  double sum(double *a, int n)

Various ways that sum( ) might be called InvocationWhat gets computed and returned sum(v, 100)v[0] + v[1] + … c … + v[99] sum(v, 88)v[0] + v[1] + … c … + v[87] sum(&v[7], k – 7)v[7] + v[8] + … c … + v[k - 1] sum(v+7, 2 * k)v[7] + v[8] + … c … + v[2 * k+6] 수행 내용

Bubble sorting Greedy method 큰 것을 먼저 뒤로 보내거나, 작은 것을 먼저 앞으로 보내거나 257(6.7 절 ) 페이지 설명

p.258 Unordered data: First pass: Second pass: Third pass: Fourth pass: Fifth pass: Sixth pass: Seventh pass:

calloc() and malloc() stdlib.h Dynamic memory allocation ( calloc : contiguous allocation, malloc : memory allocation ) Dynamically create space for arrays, structures, unions callc(n, el_size) malloc(n*el_size) 실패시 NULL 을 return (memory 가 부족하면 )

예 int *a, n; … a=calloc(n, sizeof(int)); a=malloc(n*sizeof(int)); deallocation : free(ptr) free(a); Reallocation : realloc() 261page 프로그램 설명

Memory map automatic (stack) ↓↑↓↑ malloc (heap) static external

Offsetting the pointer a = calloc(n, sizeof(double));

Offsetting the pointer a = calloc(n+1, sizeof(double)) ;

Merge sorting Merge to arrays Merge 방법 설명 (264page 프로그램 ) Merge sorting 방법 설명 (266 page) Why power of 2? 그러면 해결방법은

Strings Strings are one-dimensional array of type char A null character is a byte with all bits off (\0) char *p = “ abc ” ; A string constant is treated as a pointer –“ abc ” [1]  *( “ abc ” +1) – char *p= “ abcde ” ; – char s[] = “ abcde ” ;  char s[] = { ‘ a ’, ‘ b ’, ‘ c ’, ‘ d ’, ‘ e ’, ‘ \0 ’ };

The memory map 페이지의 word_count program 설명

String handling functions in the standard library char *strcat(char *s1, const char *s2); int strcmp(const char *s1, const char *s2); char *strcpy(char *s1, const char *s2); size_t strlen(const char *s); /* unsigned int */ strlen() 와 strcpy() 의 프로그램 (page 273, 274) Strcat() 프로그램  275page

예제 Declarations and initializations char s1[] = “ beautiful big sky country ”, s2[] = “ how now brown cow ” ; ExpressionValue strlen(s1)25 strlen(s2 + 8)9 strcmp(s1, s2)negative integer StatementsWhat gets printed printf( “ %s ”, s1 + 10);big sky country strcpy(s1 + 10, s2 + 8); strcat(s1, “ s! ” ); printf( “ %s ”, s1);beautiful brown cows!

Multidimensional arrays Examples of declarations of arraysRemarks int a[100]; b[2][7]; c[5][3][2]; a one-dimensional array a two-dimensional array a three-dimensional array

col 1col 2col 3col 4col 5 row 1a[0][0]a[0][1]a[0][2]a[0][3]a[0][4] row 2a[1][0]a[1][1]a[1][2]a[1][3]a[1][4] row 3a[2][0]a[2][1]a[2][2]a[2][3]a[2][4] Two-dimensional arrays int a[3][5]; /* row major */ row major  column major

Expressions equivalent to a[i][j] *(a[i] + j) (*(a + i)) [j] *((*(a + i)) + j) *(&a[0][0] + 5*i + j) 예제

Storage mapping function int a[3][5] a[i][j]  *(&a[0][0] + 5*i +j) int a[I][J][K} a[i][j][k]  *(&a[0][0][0] + I*J*i + J*j +k

Formal parameter declarations int a[3][5] int sum(int a[][5]) { int i,j,sum=0; for(i=0;i<3;++i) for(j=0,j<5;++j) sum +=a[i][j]; return sum; } int a[][5]  int a[3][5]  int (*a)[5]

One dimensional array parameter int b[]  int b[3]  int *b char *argv[]  char *argv[3]  char **argv Caution ::: char x[][] char **x

Three dimensional array int a[7][9][2]; a[i][j][k]  *(&a[0][0][0] + 9*2*I + 2*j + k) Parameter ::: int a[][9][2]  int a[7][9][2]  int (*a)[9][2]

Initialization int a[2][3] = {1,2,3,4,5,6};  int a[2][3] = {{1,2,3},{4,5,6}};  int a[ ] [3] = {{1,2,3},{4,5,6}}; 뒤의 0 은 쓰지 않아도 int a[2][2][3] = { {{1,1,0}, {2,2,0}} {{3,0,0}, {4,4,0}} };  int a[][2][3] = {{{1,1}, {2}}, {3}, {4,4}}}; int a[2][2][3] = {0};

The use of typedef Self documentation #define N 3] typedef double scalar; typedef scalar vector[N]; typedef scalar matrix[N][N]; scalar a; vector b; matrixc; page 283 프로그램 설명

Arrays of pointers Sorting strings :: a pointer of a pointer 285page 설명

Example

Swapping of two strings W w[j] w[i] \0\0 elppa \0\0 rof Before swapping W w[j] w[i] \0\0 elppa \0\0 rof After swapping

숙제 사람의 이름을 입력하여 순서화한다 - 1 수준 ::: 순서화만 - 2 수준 ::: 사람 이름 대신에 주소 - 3 수준 ::: 한글 이름을 입력하여 순서화

Arguments to main() int main(int argc, char *argv[]) { int i; printf( “ argc = %d\n ”, argc); for (i=0;i<argc;++i) printf(argv[%d] = %s\n ”, i argv[i]); return 0; } my_echo a is an apple argv=5, argv[0]= my_echo … argv[4] = apple

Ragged arrays char a[2][15] = { “ abc: ”, “ a is for apple ” }; char *p[2] = { “ abc: ”, “ a is for apple ” }; Ragged array ::: an array of pointers whose elements are used to point varying sizes

예 A ragged array

Functions as arguments # include “ sum_sqr.h ” double sum_square (double f(double x), int m, int n) { int k; double sum=0.0; for (k=m; k<=n;++k) sum +=f(k)*f(k); return sum; } double sum_square(double (*f)(double), int m, int n); sum += (*f)(k) * (*f)(k); 도 가능 조심 :::: double sum_square(double *f(double), int m, int n) 은 안 된다 … 함수 f(double) 의 return 값이 double 의 pointer

Function prototypes double sum_square (double f(double x), int m, int n) double sum_square (double f(double), int m, int n) double sum_square (double f(double x), int, int) double sum_square (double (*f)(double x), int, int) double sum_square (double (*)(double x), int, int) double sum_square (double g(double x), int a int b) double sum_square (double f(double x0, int m, int n)

Using bisection to find the root of a function A real number x that satisfies the equation f(x) = 0  a root of f 프로그램 설명 (298 페이지 )

Finding a root Finding a root by bisection

The Kepler equation m = x – e sin(x)  y=x and y=m + e sin(x)  x – e sin(x) – m = 0

Kepler equation A solution of the Kepler equation x0x0 x y y =x y =m+e sinx

Arrays of Pointers to Function function 은 array 의 처리와 유사 dbl (*pfdd) (dbl); pfdd = kepler; /* 302page 설명 */ Function 을 array 로 처리 pfdd f[N] = {NULL, f1, f2, f3}; /* 304page 설명 */

The type qualifier const (ANSI) static const int k=3;  can be initialized but can not be modified : K is a constant int with static storage class const int n=3; int v[n];  error const int a=7; int *p = &a;  ERROR const int a=7; const int *p =&a;  OK

The type qualifier volatile (ANSI ) A volatile object can be modified in some unspecified way by the hardware extern const volatile int real_time_clock;

숙제 수업시간 :::3, 6, 7,8, 11, 18, 24, 27, 38, 42 집 ::: 4, 10, 12, 16, 20, 32, 35 추가 ::: 다음 중 2 문제를 집에서 풀 것  29, 30,46