본문 바로가기
학습/IT

[IT] C언어 입문(9) Array와 Pointers, 배열과 포인터

by 개성공장 2021. 8. 28.
반응형

□ Arrays and Pointers(배열과 포인터)

 * Array(배열)

 - A collection of identically typed data items distinguished by their indices (or subscripts)

 - One dimensional arrays : type identifier[size];

 - lower_bound = 0,  upper bound = size - 1

 - ex) int a[10];

 

 * Array Initialization

 - one_dimentional_array_initializer ::= { initializer_list }

 - initializer_list ::= initializer { , initializer }*

 - initializer ::= constant_integral_expression

 - example

float a[3] = {0.1, 0.3, 0.5};

int a[3] = {3, 4};         => {3, 4, 0};      // 기본값은 0

int a[] = {-3, 0, 3, 5}    => int a[4]

char s[] = "abcd";       => char s[] = {'a', 'b', 'c', 'd', '\0'}     // string의 끝을 표시하기 위해 0을 사용

 

 * Accessing Array Elements

#include <stdio.h>
#define N 5    // #이 붙은 부분은 cpp를 호출하여 전처리 되는 부분, array 크기 지정

int main(void)
{
	int a[100];
	int sum = 0;
	int i, n;

	printf("enter a number     >");
	scanf("%d", &n);

	for (i=0; i<n; i++) {
		scanf("%d", &a[i]);
	}

	for (i=0; i<N; i++) {
		sum += a[i];
	}
	printf("sum = %d\n", sum);
}

 

 * Pointers(포인터)

 - Pointers are used in programs to access memory and manipulate addresses

 - The basic syntax to define a pointer is 'int *x'  -> x is a pointer to and integer

 

int *x;       // 포인터 변수 x를 선언

int a = 1;

 

x = NULL;     // 아무것도 가리키지 않음 (포인터를 초기화), 0보다는 더 의미파악이 쉬움

x = 0;           // x는 포인터 변수로 선언되었으므로 NULL과 동일한 의미

x = & a;         // 변수 a의 주소 값을 x라는 포인터 변수에 넣어라!

printf("%p %d %d\n", x, *x, sizeof(x));     // %p는 주소형태를 의미, *x는 x가 가리키는 대상의 값을 출력, 

x = (int *) 0x2345;     // 가능은 하지만 실제로 이렇게 직접 값을 넣는 경우는 거의 없음

 

 - segmentation fault : memory protection을 위반했다는 의미, 자기 것이 아닌 다른 메모리 영역을 침범하면 안 됨

※ C언어 입문 시리즈
1. Introduction - C언어의 역사와 기본 개념
2. Variables - 변수, 대입연산자, 구문규칙, 데이터타입 등
3. Data types, 데이터 타입(자료형)
4. Operators, 연산자 - scanf, 산술연산자, 관계연산자, 증감연산자, 대입연산자, 동등연산자 등
5. Operators, 연산자 - 논리연산자, 단축평가, 대입연산자, if문 및 while문 활용
6. Control flow, 제어흐름 - While문, For문, If문, do-while문 등 루프문
7. Function, 함수 - Goto문, getchar와 putchar, 함수 정의와 프로토타입 선언
8. Scope rules/recursion, 변수의 영역규칙과 재귀호출, 난수생성 예시
9. Array와 Pointers, 배열과 포인터
10. Pointer, 역참조, swap 함수 활용, 배열과 포인터 비교
11. File operation 파일연산, String, 다차원 배열 예시
12. structure, union, enumerated types - 구조체, 공용체, 열거체
13. 자료구조(data structure) 예시 - 연결리스트(linked list)
14. C 전처리기(C preprocessor), 함수 포인터(function pointer)
반응형

댓글