정보처리기사 실기/프로그래밍

C Programming

· 코딩마이데이

포인터 Example 1

#include <stdio.h>

int main()
{
	int var = 5;
	printf("var : %d\n", var);

	printf("var 주소: %p", &var);
	return 0;
}

 

실행 결과

var : 5
var 주소: 000000E56A0FFD24

 

 

 

포인터 Example 2

#include <stdio.h>

int main()
{
	int* pc, c;
	c = 5;
	pc = &c;
	printf("%d", *pc);
}

 

실행 결과

5

 

 

포인터 Example 3

#include <stdio.h>

int main()
{
	int* pc, c;
	c = 5;
	pc = &c;
	c = 1;
	printf("%d", c);
	printf("%d", *pc);
}

 

실행 결과

11

 

 

 

 

 

 

포인터 Example 5

#include <stdio.h>

int main()
{
	int* pc, c, d;
	c = 5;
	d = -15;
	pc = &c;
	printf("%d", *pc);
	pc = &d;
	printf("%d", *pc);
}

 

실행 결과

5-15

 

 

 

 

 

 

포인터 Example 6

#include <stdio.h>

int main()
{
	char a[3] = { 10, 20, 30 };
	char* p = a;
	printf("%d %d %d\n", p[0], p[1], p[2]);
	printf("%d %d %d\n", *p, *(p + 1), *(p + 2));

	printf("%c", 'A' + 1);
}

 

실행 결과

10 20 30
10 20 30
B

 

 

포인터 Example 7

#include <stdio.h>

int main()
{
	int x[5] = { 1, 2, 3, 4, 5 };
	int* ptr;

	ptr = &x[2];

	printf("*ptr = %d \n", *ptr);
	printf("%(ptr + 1) % d \n", *(ptr + 1));
	printf("*(ptr - 1) = %d", *(ptr - 1));

	return 0;
}

 

실행 결과

*ptr = 3
(ptr + 1)  4
*(ptr - 1) = 2

 

 

 

 

포인터 Example 8

#include <stdio.h>
#include <string.h>

int main()
{
	char s[] = "JungBo";
	char* p;
	p = s;
	printf("첫 번째 문자 : %c \n", *p);
	p = p + 1;
	printf("다음 문자 : % c \n", *p);
	printf("문자열의 모든 문자 인쇄 \n");
	p = s; // 포인터 재설정
	for (int i = 0; i < strlen(s); i++)
	{
		printf("%c \n", *p);
		p++;
	}
	return 0;
}

 

실행 결과

첫 번째 문자 : J
다음 문자 : u
문자열의 모든 문자 인쇄
J
u
n
g
B
o

 

 

 

 

포인터 Example 9

#include <stdio.h>

void swap(int a, int b) {
	int temp;
	temp = a;
	a = b;
	b = temp;
}

int main()
{
	int x = 5;
	int y = 3;
	printf("x = %d, y = %d\n", x, y);
	swap(x, y);
	printf("x = %d, y = %d\n", x, y);
	return 0;
}

 

실행 결과

x = 5, y = 3
x = 5, y = 3

 

 

포인터 Example 10

#include <stdio.h>

void swap(int *a, int *b) {
	int temp;
	temp = *a;
	*a = *b;
	*b = temp;
}

int main()
{
	int x = 5;
	int y = 3;
	printf("x = %d, y = %d\n", x, y);
	swap(&x, &y);
	printf("x = %d, y = %d\n", x, y);
	return 0;
}

 

실행 결과

x = 5, y = 3
x = 3, y = 5

포인터 Example 11

#include <stdio.h>

int add_All(int* p, int size) {
	int total = 0;
	for (int i = 0; i < size; i++) {
		total += p[i];
	}

	return (total);
}

int main()
{
	int Data[5] = { 10, 20, 30, 40, 50 };
	printf("Total summation is %d\n", add_All(Data, 5));
	return 0;
}

 

실행 결과

Total summation is 150