SlideShare a Scribd company logo
Array & Pointers
2
One-Dimensional Arrays
§ Array
– 같은 이름의 변수를 사용하여 여러 개의 type이 같은 값을 표현할
수 있게 하는 data type.
– num이라는 이름으로 10개의 int형 변수를 연속적으로 5개 할당
int num[5] ;
num
1000번지 1004 1008 1012 1016
3
One-Dimensional Arrays
§ Array
– 각각의 변수에는 index를 사용하여 접근 한다. index = 0가 첫 번째
원소를 의미 한다.
int num[5] ;
num[0] = 10 ;
num[1] = 13 ;
num[2] = 14 ;
num[3] = 17 ;
num[4] = 20 ;
10 13 14 17 20num
1000번지 1004 1008 1012 1016
num[0] num[1] num[2] num[3] num[4]
4
One-Dimensional Arrays
§ Array – Syntax
– 배열의 크기는 반드시 양수로 써야 한다.
– 배열 원소의 첨자는 항상 0 부터 시작한다.
• 위의 예제의 경우는 grade[0], grade[1],~ , grade[49]가 생성.
element-type array_name[size];
[Ex] int grade[50];
data type variable Name
size of Array
5
One-Dimensional Arrays
#include <stdio.h>
int main() {
int a[100], k ;
for( k = 0 ; k < 100 ; k++ )
scanf( “%d”, &a[k] ) ;
for( k = 99 ; k >= 0 ; k-- )
printf( “%d ”, a[k] ) ;
printf( “n” ) ;
return 0;
}
§ 배열사용 예제
#include <stdio.h>
int main() {
int a[100], k, sum = 0 ;
for( k = 0 ; k < 100 ; k++ )
scanf( “%d”, &a[k] ) ;
for( k = 0 ; k < 100 ; k++ )
sum += a[k] ;
printf( “%dn”, sum ) ;
return 0;
}
6
Initialization
§ 초기화
– 지정된 array에 초기값을 할당하는 것.
§ 초기값이 배열 원소의 값보다 적을 때
float x[7] = { -1.1, 0.2, 33.0, 4.4, 5.05, 0.0, 7.7 };
x[0] = -1.1, x[1] = 0.2,…, x[6] = 7.7 로 초기화된다.
int a[100] = { -1 };
a[0] = -1, a[1] = 0, … a[99] = 0처럼
남은 원소들은 모두 0으로 초기화 된다.
7
cnt_abc Program
#include <stdio.h>
#include <ctype.h>
int main(void) {
int letter[26] = {0}, c, i ;
while ( (c = getchar( )) != EOF) {
c=toupper(c);
if( isalph(c) ) ++letter[c – ‘A’];
}
for ( i = 0; i < 26; ++i) {
if ( i % 6 == 0 ) printf(“n”);
printf(“%4c:%3d”, ‘A’ + i, letter[i]);
} /* end of for */
return 0;
}
문자가 끝날때까지 getchar()로
입력받는다. 소문자는 대문자로
바꾼다.
배열에 저장된 문자들의
개수를 하나씩 출력한다.
§ 입력 받은 문자 각각의 개수를 헤아리자
8
The Relationship between Arrays and
Pointers
§ Example :
– 각 원소의 주소는 ?
int num[5] ;
num
1000번지 1004 1008 1012 1016
num[0] num[1] num[2] num[3] num[4]
&num[0] == 1000
&num[1] == 1004
&num[2] == 1008
&num[3] == 1012
&num[4] == 1016
9
The Relationship between Arrays and
Pointers
§ Example : num은 무엇일까?
– num은 포인터 상수로 “배열 시작 주소” 이다.
int num[5] ; num
1000번지 1004 1008 1012 1016
num[0] num[1] num[2] num[3] num[4]
num == &num[0] == 1000
10
The Relationship between Arrays and
Pointers
§ Example : 포인터의 특별한 연산
– “포인터 + 1” 은 “1 큰 주소값”을 의미하는 것이 아니라, 그 “다음
원소의 주소” 이다
– “포인터 - 1” 은 “바로 이전 원소의 주소” 이다
int num[5] ;
1000번지 1004 1008 1012 1016
num[0] num[1] num[2] num[3] num[4]
num == &num[0] == 1000
(num+0) == ??
(num+1) == ??
(num+2) == ??
(num+3) == ??
(num+4) == ??
&num[0]
&num[1]
&num[2]
&num[3]
&num[4]
11
The Relationship between Arrays and
Pointers
§ Example : 포인터의 특별한 연산
int num[5] ; 10 20 30 40 50
1000번지 1004 1008 1012 1016
num[0] num[1] num[2] num[3] num[4]
int num[5], *p = num ;
*p = 10 ;
*(p+1) = 20 ;
*(p+2) = 30 ;
*(p+3) = 40 ;
*(p+4) = 50 ;
int num[5], *p = num ;
p[0] = 10 ;
p[1] = 20 ;
p[2] = 30 ;
p[3] = 40 ;
p[4] = 50 ;
int num[5] ;
*num = 10 ;
*(num+1) = 20 ;
*(num+2) = 30 ;
*(num+3) = 40 ;
*(num+4) = 50 ;
int num[5] ;
num[0] =10 ;
num[1] = 20 ;
num[2] = 30 ;
num[3] = 40 ;
num[4] = 50 ;
12
Pointer Arithmetic and Element Size
§ 포인터 연산
– 변수 p가 포인터라면 p + 1은 그 type의 다음 변수를 저장하
거나 access할 수 있도록 주소를 생성한다.
– 포인터의 정수 덧셈 연산이 가능하다.
– 포인터의 정수 뺄셈 연산이 가능하다.
– 두 개의 포인터의 뺄셈 연산이 가능하다.
13
Pointer Arithmetic and Element Size
§ Adding an Integer to a Pointer
[Ex]
p = &a[2];
q = p + 3;
p += 6;
0 1 2 3 4 5 6 7 8 9
p
a
0 1 2 3 4 5 6 7 8 9
p
a
0 1 2 3 4 5 6 7 8 9
p
a
q
q
14
Pointer Arithmetic and Element Size
§ Subtracting an Integer from a Pointer
[Ex]
p = &a[8];
q = p - 3;
p -= 6;
0 1 2 3 4 5 6 7 8 9
p
a
0 1 2 3 4 5 6 7 8 9
p
a
0 1 2 3 4 5 6 7 8 9
p
a
q
q
15
Pointer Arithmetic and Element Size
§ Subtracting Pointers
[Ex]
p = &a[5];
q = &a[1];
i = p – q; /* i == 4 */
i = q – p; /* i == -4 */
0 1 2 3 4 5 6 7 8 9
q
a
p
16
Pointer Arithmetic and Element Size
§ Comparing Pointers
– 관계연산자 (relational operators) <, <=, >,>= 사용 가능.
– 동등연산자(equality operators) ==, != 사용 가능.
[Ex]
p = &a[5];
q = &a[1];
p <= q; /* result is 0 */
p >= q; /* result is 1 */
17
Pointer Arithmetic and Element Size
§ 포인터 연산의 예제
int a[ ] = { 5,15,25,43,12,1,7,89,32,11}
int *p = &a[1], *q = &a[5] ;
1. *(p + 3) ?
2. *(q - 2) ?
3. q - p ?
4. if ( p > q ) ?
5. if ( *p > *q )?
18
Pointer Arithmetic and Element Size
§ 포인터 연산의 예제
#include <stdio.h>
int main(void)
{
double a[2], *p, *q;
p = &a[0]; /* points at base of array */
q = p + 1; /* equivalent to q = &a[1]; */
printf(“%dn”, q – p );
printf(“%dn”, (int) q – (int) p );
printf(“%dn”, sizeof(double) );
return 0;
}
Combining the * and ++ Operators
§ Combining the * and ++ Operators
– p를 1 증가 혹는 감소 시킨 후 *p
– *p 후 p를 1 증가 혹은 감소
– p가 가르키는 변수를 1 증가 혹은 감소
19
*++p º *(++p), *--p º *(--p)
*p++ º *(p++), *p-- º *(p--)
(*p)++, (*p)--
Combining the * and ++ Operators
§ Combining the * and ++ Operators
20
int main()
{
int k, a[10], *p = a ;
while( p < &a[10] )
*p++ = 0 ;
return 0;
}
int main()
{
int k, a[10], *p = a ;
while( p < &a[10] ) {
*p = 0 ;
p = p + 1 ;
}
return 0;
}
Combining the * and ++ Operators
§ Combining the * and ++ Operators
21
int main()
{
int k, a[10], *p = &a[10] ;
while( p >= &a[0] )
*--p = 0 ;
return 0;
}
int main()
{
int k, a[10], *p = a ;
while( p >= &a[0] ) {
p = p -1 ;
*p = 0 ;
}
return 0;
}
Example
§ 입력 받은 수 더하기
22
#include <stdio.h>
int sum( int num[], int size ) {
int k, sum = 0 ;
for( k = 0 ; k < size ; k++ )
sum += num[k] ;
return sum ;
}
int main() {
int a[100], k ;
for( k = 0 ; k < 100 ; k++ )
scanf( “%d”, &a[k] ) ;
printf( “%dn”, sum(a, 100) ) ;
return 0;
}
#include <stdio.h>
int sum( int num[], int size ) {
int k, sum = 0 ;
for( k = 0 ; k < size ; k++ )
sum += *num++ ;
return sum ;
}
int main() {
int a[100], k ;
for( k = 0 ; k < 100 ; k++ )
scanf( “%d”, &a[k] ) ;
printf( “%dn”, sum(a, 100) ) ;
return 0;
}
int num[]는
int *num과 같다.

More Related Content

What's hot

Project#5 최단거리 찾기 D0 Hwp
Project#5 최단거리 찾기 D0 HwpProject#5 최단거리 찾기 D0 Hwp
Project#5 최단거리 찾기 D0 HwpKimjeongmoo
 
R 프로그래밍 기본 문법
R 프로그래밍 기본 문법R 프로그래밍 기본 문법
R 프로그래밍 기본 문법
Terry Cho
 
이산수학 C1 프로젝트 5
이산수학 C1 프로젝트 5이산수학 C1 프로젝트 5
이산수학 C1 프로젝트 5pkok15
 
자료구조 프로젝트
자료구조 프로젝트자료구조 프로젝트
자료구조 프로젝트
hyungoh kim
 
이산수학 C1 프로젝트 4
이산수학 C1 프로젝트 4이산수학 C1 프로젝트 4
이산수학 C1 프로젝트 4pkok15
 
Insert Sort Algorithm (삽입 정렬 알고리즘)
Insert Sort Algorithm (삽입 정렬 알고리즘)Insert Sort Algorithm (삽입 정렬 알고리즘)
Insert Sort Algorithm (삽입 정렬 알고리즘)
Junyeong Choi
 
Data Structure - 1st Study
Data Structure - 1st StudyData Structure - 1st Study
Data Structure - 1st Study
Chris Ohk
 
Python 스터디
Python 스터디Python 스터디
Python 스터디
sanghyuck Na
 
2021 2학기 정기 세미나 4주차
2021 2학기 정기 세미나 4주차2021 2학기 정기 세미나 4주차
2021 2학기 정기 세미나 4주차
Moonki Choi
 
R 기본-데이타형 소개
R 기본-데이타형 소개R 기본-데이타형 소개
R 기본-데이타형 소개
Terry Cho
 
Initializer list
Initializer listInitializer list
Initializer list
Seonmun Choi
 
2012 Dm C3 03
2012 Dm C3 032012 Dm C3 03
2012 Dm C3 03chl132435
 
R 스터디 네번째
R 스터디 네번째R 스터디 네번째
R 스터디 네번째
Jaeseok Park
 
R 스터디 첫번째
R 스터디 첫번째R 스터디 첫번째
R 스터디 첫번째
Jaeseok Park
 
R 프로그래밍-향상된 데이타 조작
R 프로그래밍-향상된 데이타 조작R 프로그래밍-향상된 데이타 조작
R 프로그래밍-향상된 데이타 조작
Terry Cho
 
R 프로그램의 이해와 활용 v1.1
R 프로그램의 이해와 활용 v1.1R 프로그램의 이해와 활용 v1.1
R 프로그램의 이해와 활용 v1.1
happychallenge
 

What's hot (20)

이산수학05
이산수학05이산수학05
이산수학05
 
Project#5 최단거리 찾기 D0 Hwp
Project#5 최단거리 찾기 D0 HwpProject#5 최단거리 찾기 D0 Hwp
Project#5 최단거리 찾기 D0 Hwp
 
R 프로그래밍 기본 문법
R 프로그래밍 기본 문법R 프로그래밍 기본 문법
R 프로그래밍 기본 문법
 
이산수학 C1 프로젝트 5
이산수학 C1 프로젝트 5이산수학 C1 프로젝트 5
이산수학 C1 프로젝트 5
 
자료구조 프로젝트
자료구조 프로젝트자료구조 프로젝트
자료구조 프로젝트
 
이산수학 C1 프로젝트 4
이산수학 C1 프로젝트 4이산수학 C1 프로젝트 4
이산수학 C1 프로젝트 4
 
Ruby 2 array_hash
Ruby 2 array_hashRuby 2 array_hash
Ruby 2 array_hash
 
Insert Sort Algorithm (삽입 정렬 알고리즘)
Insert Sort Algorithm (삽입 정렬 알고리즘)Insert Sort Algorithm (삽입 정렬 알고리즘)
Insert Sort Algorithm (삽입 정렬 알고리즘)
 
Data Structure - 1st Study
Data Structure - 1st StudyData Structure - 1st Study
Data Structure - 1st Study
 
Python 스터디
Python 스터디Python 스터디
Python 스터디
 
2021 2학기 정기 세미나 4주차
2021 2학기 정기 세미나 4주차2021 2학기 정기 세미나 4주차
2021 2학기 정기 세미나 4주차
 
R 기본-데이타형 소개
R 기본-데이타형 소개R 기본-데이타형 소개
R 기본-데이타형 소개
 
Initializer list
Initializer listInitializer list
Initializer list
 
2012 Dm C3 03
2012 Dm C3 032012 Dm C3 03
2012 Dm C3 03
 
R 스터디 네번째
R 스터디 네번째R 스터디 네번째
R 스터디 네번째
 
R 스터디 첫번째
R 스터디 첫번째R 스터디 첫번째
R 스터디 첫번째
 
R 프로그래밍-향상된 데이타 조작
R 프로그래밍-향상된 데이타 조작R 프로그래밍-향상된 데이타 조작
R 프로그래밍-향상된 데이타 조작
 
R intro
R introR intro
R intro
 
R_datamining
R_dataminingR_datamining
R_datamining
 
R 프로그램의 이해와 활용 v1.1
R 프로그램의 이해와 활용 v1.1R 프로그램의 이해와 활용 v1.1
R 프로그램의 이해와 활용 v1.1
 

Viewers also liked

15 3. modulization
15 3. modulization15 3. modulization
15 3. modulization웅식 전
 
13. structure
13. structure13. structure
13. structure
웅식 전
 
12 2. dynamic allocation
12 2. dynamic allocation12 2. dynamic allocation
12 2. dynamic allocation웅식 전
 
15 2. arguement passing to main
15 2. arguement passing to main15 2. arguement passing to main
15 2. arguement passing to main웅식 전
 
11장 상속
11장 상속11장 상속
11장 상속
유석 남
 
Week12 chapter11
Week12 chapter11 Week12 chapter11
Week12 chapter11 웅식 전
 
12장 상속 (고급)
12장 상속 (고급)12장 상속 (고급)
12장 상속 (고급)
유석 남
 

Viewers also liked (8)

15 3. modulization
15 3. modulization15 3. modulization
15 3. modulization
 
13. structure
13. structure13. structure
13. structure
 
12 2. dynamic allocation
12 2. dynamic allocation12 2. dynamic allocation
12 2. dynamic allocation
 
15 2. arguement passing to main
15 2. arguement passing to main15 2. arguement passing to main
15 2. arguement passing to main
 
14. fiile io
14. fiile io14. fiile io
14. fiile io
 
11장 상속
11장 상속11장 상속
11장 상속
 
Week12 chapter11
Week12 chapter11 Week12 chapter11
Week12 chapter11
 
12장 상속 (고급)
12장 상속 (고급)12장 상속 (고급)
12장 상속 (고급)
 

Similar to 11. array & pointer

Example
ExampleExample
Example
유석 남
 
2012 Ds D0 01 Pdf
2012 Ds D0 01 Pdf2012 Ds D0 01 Pdf
2012 Ds D0 01 Pdfkd19h
 
2012 Ds D0 01
2012 Ds D0 012012 Ds D0 01
2012 Ds D0 01chl132435
 
2012 Dm A0 02 Pdf
2012 Dm A0 02 Pdf2012 Dm A0 02 Pdf
2012 Dm A0 02 Pdfkd19h
 
2012 Dm A0 02 Pdf
2012 Dm A0 02 Pdf2012 Dm A0 02 Pdf
2012 Dm A0 02 Pdfjinwookhong
 
프로젝트 보고서
프로젝트 보고서프로젝트 보고서
프로젝트 보고서
hyungoh kim
 
2012 Dm A0 04 Pdf
2012 Dm A0 04 Pdf2012 Dm A0 04 Pdf
2012 Dm A0 04 Pdfjinwookhong
 
Cpp 0x kimRyungee
Cpp 0x kimRyungeeCpp 0x kimRyungee
Cpp 0x kimRyungeescor7910
 
이산수학 C1 프로젝트 3
이산수학 C1 프로젝트 3이산수학 C1 프로젝트 3
이산수학 C1 프로젝트 3pkok15
 
3콤비네이션
3콤비네이션3콤비네이션
3콤비네이션
herojoon1378
 
2012 Ds B1 01
2012 Ds B1 012012 Ds B1 01
2012 Ds B1 01seonhyung
 
Project#3 How Fast Can We Sort Hwp
Project#3 How Fast Can We Sort HwpProject#3 How Fast Can We Sort Hwp
Project#3 How Fast Can We Sort HwpKimjeongmoo
 
Data Structure 3
Data Structure 3Data Structure 3
Data Structure 3yonsei
 
과제 1,2,3
과제 1,2,3과제 1,2,3
과제 1,2,3mil23
 
Fp basic-kotlin
Fp basic-kotlinFp basic-kotlin
Fp basic-kotlin
Myeongin Woo
 

Similar to 11. array & pointer (20)

Example
ExampleExample
Example
 
3.포인터
3.포인터3.포인터
3.포인터
 
2012 Ds D0 01 Pdf
2012 Ds D0 01 Pdf2012 Ds D0 01 Pdf
2012 Ds D0 01 Pdf
 
2012 Ds D0 01
2012 Ds D0 012012 Ds D0 01
2012 Ds D0 01
 
이산치2번
이산치2번이산치2번
이산치2번
 
2012 Dm A0 02 Pdf
2012 Dm A0 02 Pdf2012 Dm A0 02 Pdf
2012 Dm A0 02 Pdf
 
2012 Dm A0 02 Pdf
2012 Dm A0 02 Pdf2012 Dm A0 02 Pdf
2012 Dm A0 02 Pdf
 
프로젝트 보고서
프로젝트 보고서프로젝트 보고서
프로젝트 보고서
 
이산수학03
이산수학03이산수학03
이산수학03
 
C review
C  reviewC  review
C review
 
2012 Dm A0 04 Pdf
2012 Dm A0 04 Pdf2012 Dm A0 04 Pdf
2012 Dm A0 04 Pdf
 
Cpp 0x kimRyungee
Cpp 0x kimRyungeeCpp 0x kimRyungee
Cpp 0x kimRyungee
 
이산수학 C1 프로젝트 3
이산수학 C1 프로젝트 3이산수학 C1 프로젝트 3
이산수학 C1 프로젝트 3
 
3콤비네이션
3콤비네이션3콤비네이션
3콤비네이션
 
2012 Ds B1 01
2012 Ds B1 012012 Ds B1 01
2012 Ds B1 01
 
이산치1번
이산치1번이산치1번
이산치1번
 
Project#3 How Fast Can We Sort Hwp
Project#3 How Fast Can We Sort HwpProject#3 How Fast Can We Sort Hwp
Project#3 How Fast Can We Sort Hwp
 
Data Structure 3
Data Structure 3Data Structure 3
Data Structure 3
 
과제 1,2,3
과제 1,2,3과제 1,2,3
과제 1,2,3
 
Fp basic-kotlin
Fp basic-kotlinFp basic-kotlin
Fp basic-kotlin
 

More from 웅식 전

10. pointer & function
10. pointer & function10. pointer & function
10. pointer & function웅식 전
 
7. variable scope rule,-storage_class
7. variable scope rule,-storage_class7. variable scope rule,-storage_class
7. variable scope rule,-storage_class웅식 전
 
6. function
6. function6. function
6. function
웅식 전
 
5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing웅식 전
 
5 1. character processing
5 1. character processing5 1. character processing
5 1. character processing웅식 전
 
15 1. enumeration, typedef
15 1. enumeration, typedef15 1. enumeration, typedef
15 1. enumeration, typedef웅식 전
 
3 2. if statement
3 2. if statement3 2. if statement
3 2. if statement웅식 전
 
3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib웅식 전
 
2 3. standard io
2 3. standard io2 3. standard io
2 3. standard io웅식 전
 
2 2. operators
2 2. operators2 2. operators
2 2. operators웅식 전
 
2 1. variables & data types
2 1. variables & data types2 1. variables & data types
2 1. variables & data types웅식 전
 
Goorm ide 교육용버전 for skku(학생)
Goorm ide 교육용버전 for skku(학생)Goorm ide 교육용버전 for skku(학생)
Goorm ide 교육용버전 for skku(학생)웅식 전
 
구름 기본 소개자료
구름 기본 소개자료구름 기본 소개자료
구름 기본 소개자료웅식 전
 
Goorm ide 소개 슬라이드(교육용 버전)
Goorm ide 소개 슬라이드(교육용 버전)Goorm ide 소개 슬라이드(교육용 버전)
Goorm ide 소개 슬라이드(교육용 버전)웅식 전
 
13th chapter12 slide
13th chapter12 slide13th chapter12 slide
13th chapter12 slide웅식 전
 
10장 문자열클래스와파일클래스
10장 문자열클래스와파일클래스10장 문자열클래스와파일클래스
10장 문자열클래스와파일클래스웅식 전
 

More from 웅식 전 (20)

10. pointer & function
10. pointer & function10. pointer & function
10. pointer & function
 
9. pointer
9. pointer9. pointer
9. pointer
 
7. variable scope rule,-storage_class
7. variable scope rule,-storage_class7. variable scope rule,-storage_class
7. variable scope rule,-storage_class
 
6. function
6. function6. function
6. function
 
5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing
 
5 1. character processing
5 1. character processing5 1. character processing
5 1. character processing
 
15 1. enumeration, typedef
15 1. enumeration, typedef15 1. enumeration, typedef
15 1. enumeration, typedef
 
4. loop
4. loop4. loop
4. loop
 
3 2. if statement
3 2. if statement3 2. if statement
3 2. if statement
 
3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib
 
2 3. standard io
2 3. standard io2 3. standard io
2 3. standard io
 
2 2. operators
2 2. operators2 2. operators
2 2. operators
 
2 1. variables & data types
2 1. variables & data types2 1. variables & data types
2 1. variables & data types
 
Goorm ide 교육용버전 for skku(학생)
Goorm ide 교육용버전 for skku(학생)Goorm ide 교육용버전 for skku(학생)
Goorm ide 교육용버전 for skku(학생)
 
구름 기본 소개자료
구름 기본 소개자료구름 기본 소개자료
구름 기본 소개자료
 
Goorm ide 소개 슬라이드(교육용 버전)
Goorm ide 소개 슬라이드(교육용 버전)Goorm ide 소개 슬라이드(교육용 버전)
Goorm ide 소개 슬라이드(교육용 버전)
 
W14 chap13
W14 chap13W14 chap13
W14 chap13
 
13th chapter12 slide
13th chapter12 slide13th chapter12 slide
13th chapter12 slide
 
10장 문자열클래스와파일클래스
10장 문자열클래스와파일클래스10장 문자열클래스와파일클래스
10장 문자열클래스와파일클래스
 
10th
10th10th
10th
 

11. array & pointer

  • 2. 2 One-Dimensional Arrays § Array – 같은 이름의 변수를 사용하여 여러 개의 type이 같은 값을 표현할 수 있게 하는 data type. – num이라는 이름으로 10개의 int형 변수를 연속적으로 5개 할당 int num[5] ; num 1000번지 1004 1008 1012 1016
  • 3. 3 One-Dimensional Arrays § Array – 각각의 변수에는 index를 사용하여 접근 한다. index = 0가 첫 번째 원소를 의미 한다. int num[5] ; num[0] = 10 ; num[1] = 13 ; num[2] = 14 ; num[3] = 17 ; num[4] = 20 ; 10 13 14 17 20num 1000번지 1004 1008 1012 1016 num[0] num[1] num[2] num[3] num[4]
  • 4. 4 One-Dimensional Arrays § Array – Syntax – 배열의 크기는 반드시 양수로 써야 한다. – 배열 원소의 첨자는 항상 0 부터 시작한다. • 위의 예제의 경우는 grade[0], grade[1],~ , grade[49]가 생성. element-type array_name[size]; [Ex] int grade[50]; data type variable Name size of Array
  • 5. 5 One-Dimensional Arrays #include <stdio.h> int main() { int a[100], k ; for( k = 0 ; k < 100 ; k++ ) scanf( “%d”, &a[k] ) ; for( k = 99 ; k >= 0 ; k-- ) printf( “%d ”, a[k] ) ; printf( “n” ) ; return 0; } § 배열사용 예제 #include <stdio.h> int main() { int a[100], k, sum = 0 ; for( k = 0 ; k < 100 ; k++ ) scanf( “%d”, &a[k] ) ; for( k = 0 ; k < 100 ; k++ ) sum += a[k] ; printf( “%dn”, sum ) ; return 0; }
  • 6. 6 Initialization § 초기화 – 지정된 array에 초기값을 할당하는 것. § 초기값이 배열 원소의 값보다 적을 때 float x[7] = { -1.1, 0.2, 33.0, 4.4, 5.05, 0.0, 7.7 }; x[0] = -1.1, x[1] = 0.2,…, x[6] = 7.7 로 초기화된다. int a[100] = { -1 }; a[0] = -1, a[1] = 0, … a[99] = 0처럼 남은 원소들은 모두 0으로 초기화 된다.
  • 7. 7 cnt_abc Program #include <stdio.h> #include <ctype.h> int main(void) { int letter[26] = {0}, c, i ; while ( (c = getchar( )) != EOF) { c=toupper(c); if( isalph(c) ) ++letter[c – ‘A’]; } for ( i = 0; i < 26; ++i) { if ( i % 6 == 0 ) printf(“n”); printf(“%4c:%3d”, ‘A’ + i, letter[i]); } /* end of for */ return 0; } 문자가 끝날때까지 getchar()로 입력받는다. 소문자는 대문자로 바꾼다. 배열에 저장된 문자들의 개수를 하나씩 출력한다. § 입력 받은 문자 각각의 개수를 헤아리자
  • 8. 8 The Relationship between Arrays and Pointers § Example : – 각 원소의 주소는 ? int num[5] ; num 1000번지 1004 1008 1012 1016 num[0] num[1] num[2] num[3] num[4] &num[0] == 1000 &num[1] == 1004 &num[2] == 1008 &num[3] == 1012 &num[4] == 1016
  • 9. 9 The Relationship between Arrays and Pointers § Example : num은 무엇일까? – num은 포인터 상수로 “배열 시작 주소” 이다. int num[5] ; num 1000번지 1004 1008 1012 1016 num[0] num[1] num[2] num[3] num[4] num == &num[0] == 1000
  • 10. 10 The Relationship between Arrays and Pointers § Example : 포인터의 특별한 연산 – “포인터 + 1” 은 “1 큰 주소값”을 의미하는 것이 아니라, 그 “다음 원소의 주소” 이다 – “포인터 - 1” 은 “바로 이전 원소의 주소” 이다 int num[5] ; 1000번지 1004 1008 1012 1016 num[0] num[1] num[2] num[3] num[4] num == &num[0] == 1000 (num+0) == ?? (num+1) == ?? (num+2) == ?? (num+3) == ?? (num+4) == ?? &num[0] &num[1] &num[2] &num[3] &num[4]
  • 11. 11 The Relationship between Arrays and Pointers § Example : 포인터의 특별한 연산 int num[5] ; 10 20 30 40 50 1000번지 1004 1008 1012 1016 num[0] num[1] num[2] num[3] num[4] int num[5], *p = num ; *p = 10 ; *(p+1) = 20 ; *(p+2) = 30 ; *(p+3) = 40 ; *(p+4) = 50 ; int num[5], *p = num ; p[0] = 10 ; p[1] = 20 ; p[2] = 30 ; p[3] = 40 ; p[4] = 50 ; int num[5] ; *num = 10 ; *(num+1) = 20 ; *(num+2) = 30 ; *(num+3) = 40 ; *(num+4) = 50 ; int num[5] ; num[0] =10 ; num[1] = 20 ; num[2] = 30 ; num[3] = 40 ; num[4] = 50 ;
  • 12. 12 Pointer Arithmetic and Element Size § 포인터 연산 – 변수 p가 포인터라면 p + 1은 그 type의 다음 변수를 저장하 거나 access할 수 있도록 주소를 생성한다. – 포인터의 정수 덧셈 연산이 가능하다. – 포인터의 정수 뺄셈 연산이 가능하다. – 두 개의 포인터의 뺄셈 연산이 가능하다.
  • 13. 13 Pointer Arithmetic and Element Size § Adding an Integer to a Pointer [Ex] p = &a[2]; q = p + 3; p += 6; 0 1 2 3 4 5 6 7 8 9 p a 0 1 2 3 4 5 6 7 8 9 p a 0 1 2 3 4 5 6 7 8 9 p a q q
  • 14. 14 Pointer Arithmetic and Element Size § Subtracting an Integer from a Pointer [Ex] p = &a[8]; q = p - 3; p -= 6; 0 1 2 3 4 5 6 7 8 9 p a 0 1 2 3 4 5 6 7 8 9 p a 0 1 2 3 4 5 6 7 8 9 p a q q
  • 15. 15 Pointer Arithmetic and Element Size § Subtracting Pointers [Ex] p = &a[5]; q = &a[1]; i = p – q; /* i == 4 */ i = q – p; /* i == -4 */ 0 1 2 3 4 5 6 7 8 9 q a p
  • 16. 16 Pointer Arithmetic and Element Size § Comparing Pointers – 관계연산자 (relational operators) <, <=, >,>= 사용 가능. – 동등연산자(equality operators) ==, != 사용 가능. [Ex] p = &a[5]; q = &a[1]; p <= q; /* result is 0 */ p >= q; /* result is 1 */
  • 17. 17 Pointer Arithmetic and Element Size § 포인터 연산의 예제 int a[ ] = { 5,15,25,43,12,1,7,89,32,11} int *p = &a[1], *q = &a[5] ; 1. *(p + 3) ? 2. *(q - 2) ? 3. q - p ? 4. if ( p > q ) ? 5. if ( *p > *q )?
  • 18. 18 Pointer Arithmetic and Element Size § 포인터 연산의 예제 #include <stdio.h> int main(void) { double a[2], *p, *q; p = &a[0]; /* points at base of array */ q = p + 1; /* equivalent to q = &a[1]; */ printf(“%dn”, q – p ); printf(“%dn”, (int) q – (int) p ); printf(“%dn”, sizeof(double) ); return 0; }
  • 19. Combining the * and ++ Operators § Combining the * and ++ Operators – p를 1 증가 혹는 감소 시킨 후 *p – *p 후 p를 1 증가 혹은 감소 – p가 가르키는 변수를 1 증가 혹은 감소 19 *++p º *(++p), *--p º *(--p) *p++ º *(p++), *p-- º *(p--) (*p)++, (*p)--
  • 20. Combining the * and ++ Operators § Combining the * and ++ Operators 20 int main() { int k, a[10], *p = a ; while( p < &a[10] ) *p++ = 0 ; return 0; } int main() { int k, a[10], *p = a ; while( p < &a[10] ) { *p = 0 ; p = p + 1 ; } return 0; }
  • 21. Combining the * and ++ Operators § Combining the * and ++ Operators 21 int main() { int k, a[10], *p = &a[10] ; while( p >= &a[0] ) *--p = 0 ; return 0; } int main() { int k, a[10], *p = a ; while( p >= &a[0] ) { p = p -1 ; *p = 0 ; } return 0; }
  • 22. Example § 입력 받은 수 더하기 22 #include <stdio.h> int sum( int num[], int size ) { int k, sum = 0 ; for( k = 0 ; k < size ; k++ ) sum += num[k] ; return sum ; } int main() { int a[100], k ; for( k = 0 ; k < 100 ; k++ ) scanf( “%d”, &a[k] ) ; printf( “%dn”, sum(a, 100) ) ; return 0; } #include <stdio.h> int sum( int num[], int size ) { int k, sum = 0 ; for( k = 0 ; k < size ; k++ ) sum += *num++ ; return sum ; } int main() { int a[100], k ; for( k = 0 ; k < 100 ; k++ ) scanf( “%d”, &a[k] ) ; printf( “%dn”, sum(a, 100) ) ; return 0; } int num[]는 int *num과 같다.