#title Cpp 기초 [[TableOfContents]] ==== 전역변수 ==== * 전역변수: a, 지역변수: a 일 경우 영역 연산자 ::를 사용하면 전역변수에 접근 할 수 있다. * 서로다른 파일의 같은 이름의 전역변수 사용은 static으로 선언한다 * 다른 파일의 전역변수를 사용(#include "file1.c", file.c의 전역변수 a를 file2.c에서 사용)은 extern 으로 선언 ==== 2차원 배열의 포인터에 의한 접근 ==== {{{ #include using namespace std; int main() { int arr[2][3] = {{1,2,3},{4,5,6}}; for(int i=0; i < sizeof(arr)/sizeof(*(arr+1)); i++) { for(int j=0; j < sizeof(*(arr+1))/sizeof(int);j++) { cout << **(arr+i)+j << endl; } } /* int* pArr = &arr[0][0]; for(int i = 0; i < sizeof(arr)/sizeof(int);i++) { cout << *(pArr+i); } */ return 0; } }}} {{{ //함수인자로 넘기기 #include using namespace std; void show(int (*p)[3], int n) { for(int i=0; i < n/sizeof(*p); i++) { for(int j=0;j < sizeof(*p)/sizeof(int); j++) cout << *(*(p+i))+j << endl; } } int main() { int arr[2][3] = {{1,2,3},{4,5,6}}; show(arr, sizeof(arr)); return 0; } }}} ==== File 입/출력 ==== {{{ #include #include using namespace std; int main() { //입력 ofstream outFile("c:\\my.txt", ios::out); if(!outFile) { cerr << "cannot open my.txt" << endl; return 1; } int n = 50; float f = 20.3f; outFile << "n:" << n << endl; outFile << "f:" << f << endl; outFile.close(); //출력 ifstream inFile; char s[80]; inFile.open("c:\\my.txt", ios::in); if(!inFile) { cerr << "cannot open my.txt" << endl; return 1; } while (!inFile.eof()) { inFile >> s; cout << s << endl; } inFile.close(); return 0; } }}} ==== 매개변수 ==== * Call by value * Call by Reference ==== Function overloading ==== 이름이 같고, 시그니처가 다른 함수가 존재가능 * int max(int, int) * int max(int, int, int) * int max(float, int) ==== inline function ==== inline int sum(a int, b int) { return a+b; } 이렇게 inline 키워드를 사용하면 i = sum(10, 20); 문장은 i = 10 + 20; 으로 대체된다. 프로그램이 수행될 때 함수를 호출하고 인자를 복사하는 오버헤드를 없앤다. ==== 동적 메모리 할당 ==== {{{ #include #include using namespace std; int main(int argc, char *argv[]) { //동적 메모리 할당 int *jp = new int[10]; //원하는 객체를 생성할 수 없으면 0을 반환 if(jp == 0) cerr << "memory not allocated!" << endl; cout << "jp: " << jp << endl; cout << "jp[0]: " << &jp[0] << endl; if (jp == &jp[0]) cout << "주소가 같다" << endl; else cout << "주소가 다르다" << endl; delete []jp; //동적배열 삭제는 반드시 []를 붙여줘야 함. system("PAUSE"); return EXIT_SUCCESS; } }}} ==== 동적배열과 main함수매개변수 사용예 ==== {{{ #include #include //atoi 사용을 위해 #include //memset 사용을 위해 int main(int argc,char* argv[]) { //인자가 있어야 함 if(argc <2) { printf("Usage : 1_4_2 [integer]\n"); return 0; } //주어진 인자는 2보다 큰 수여야 함. int n = atoi(argv[1]); if(n<2) { printf("Error : n must be greater than 1\n"); return 0; } int *parray int i, j; //메모리 할당 parray = new int [n+1]; if(parray == 0) { printf("Error : memory allocation failed\n"); return 0; } //메모리를 0으로 초기화 memset(parray,0,sizeof(int)*(n+1)); for(i=2;i<=n;i++) { if(parray[i] == 1) continue; j=i; //i를 기점으로 while((j+=i)<=n) { parray[j] = 1; //i의 배수들을 모두 소수가 아니라고 마킹 } } //소수의 출력 for(i=2;i<=n;i++) { if(parray[i] == 0) printf("%d ",i); } printf("\n"); //할당된 메모리 전체를 해제 delete [] parray; return 0; } }}}