라벨이 C인 게시물 표시

C언어 fwrite() fread()로 enum, struct 읽고 쓰기

#include <stdio.h> #include <errno.h> #include <string.h> typedef enum _product_size {SIZE_S = 1 , SIZE_M, SIZE_L, SIZE_XL, SIZE_XXL} PRODUCT_SIZE; typedef enum _product_type {TYPE_OUTER= 1 , TYPE_TOP, TYPE_BOTTOM} PRODUCT_TYPE; typedef struct _cloth { char product_name[ 64 ]; unsigned product_price; char brand_name[ 64 ]; PRODUCT_TYPE product_type; PRODUCT_SIZE product_size; } cloth; void printPS (PRODUCT_SIZE ps); void printPT (PRODUCT_TYPE pt); int main ( int argc, char const *argv[]) { /* code */ FILE *outfile = NULL ; FILE *infile = NULL ; int i = 0 ; int num_cloth = 0 ; cloth temp_product = { 0 }; printf ( "How many products are here?" ); scanf ( "%d" , &num_cloth); if (num_cloth > 0 ){ outfile = fopen ( "C: \\ temp \\ cloth.dat" , "w" ); if ( NULL != outfile){ ...

C언어 Union과 Enum

#include <stdio.h> typedef enum _GradeType { TYPE_GRADE, TYPE_SCORE} GradeType; typedef struct _my_score { GradeType type; union { char grade; int score; } result; } my_score; int main () { int grade_type = TYPE_GRADE; my_score s1 = { 0 }; printf ( "GradeType input : ( 0 : Grade, 1 : Score)?" ); scanf ( "%d" , &grade_type); switch (grade_type){ case TYPE_GRADE: { char temp[ 10 ] = { 0 }; printf ( "input Grade ( A ~ F )" ); scanf ( "%s" , temp); s1. result . grade = temp[ 0 ]; break ; } case TYPE_SCORE: printf ( "input Score ( 0 ~ 100 )" ); scanf ( "%d" , &s1. result . score ); break ; default : printf ( "Wrong Type" ); ...

C 언어 함수에 구조체 변수 전달과 반환

#include <stdio.h> #include <stdlib.h> #include <string.h> struct s_student { char name[ 20 ]; int age; long number; }; void print_student_info ( struct s_student student); void input_student_info ( struct s_student *pStudent); int main ( int argc, char const *argv[]) { /* code */ struct s_student student = { "NAM" , 28 , 60121315 }; printf ( "Initial Value \n " ); print_student_info (student); input_student_info (&student); printf ( "After Calling Function input_student_inf() \n " ); print_student_info (student); return 0 ; } void print_student_info ( struct s_student student) { printf ( "Name : %s \t Age : %d \t Number : %ld \n " , student. name , student. age , student. number ); } void input_student_info ( struct s_student * pStudent) { if ( NULL != pStudent) { printf ( "Student Name ? " ); scanf ( "%s...

Visual Studio Code Window에서 C/C++ 빌드및 실행

이미지
비주얼 스튜디오 코드는 이미 설치가 끝났다는 전제하에 그리고 한글팩을 이미 설치했다는 전제하에서 진행해보겠습니다. C/C++을 지원해주는 확장팩을 깔아줍니다. 그리고 윈도우용 gcc, g++ 컴파일러를 설치해줍니다. 아래 사진참고 Installer를 실행한 다음, 아래사진과 같이 초록색으로 마킹 되어 있는 것들을 체크후 설치 해줍니다. 아래사진은 이미 설치하고 나서의 화면입니다. 그리고 환경변수 Path에 MinGW 설치경로를 잡아줍니다. 설치 후 cmd에 확인! 아래의 간단한 코드를 빌드하고 실행해보겠다. 아래와 같이 터미널탭에서 빌드 작업 실행을 누른다. 아래와 같은 화면이 뜨는데 오른쪽 빌드 작업 구성... 을 클릭한다. 아래처럼 바뀌는데 Others를 다시 클릭한다. 그리고 아래처럼 바뀌면 다시 클릭 그러면 아래와 같이 tasks.json 파일이 생성된다. 아래 처럼 코드를 바꾼다. 두가지 task가 있는데 build_c, exec_c 이다. 직관적인 이름 그자체로 build_c는 c언어로 짜여진 소스를 컴파일 해주는 작업이고 exec_c는 컴파일된 파일을 실행시켜주는 작업이다. 이제 아까 했던 터미널탭에서 빌드 작업을 실행 하고, 그다음 작업 실행을 누르고 exec_c를 선택하면 아래처럼 빌드 하고 실행한다. 혹시 더 괜찮은 방법이 있으면 댓글로 알려주세요~ 아래 블로그를 참고해서 제가 직접 실습한 것을 블로깅했습니다. http://webnautes.tistory.com/1158 그럼 이만 허접의 기록입니다.

C 언어 구조체 배열의 동적 할당

포인터변수를 선언하고 malloc()함수를 사용해서 메모리를 할당하고 free()함수로 해제 #include <stdio.h> #include <stdlib.h> struct s_teacher {         char name[20];         int age;         long number; }; struct s_student {         char name[20];         int age;         long number;         struct s_teacher* pTeacher; //포인터 변수 }; void inputCounts(int *sCnt, int *tCnt); int main() {         int sCnt =0, tCnt =0;         inputCounts(&sCnt, &tCnt);         if(sCnt <= 0 || tCnt <= 0)         {                 printf("선생과 학생수는 1명 이상이여야 됩니다.\n");                 return 0;         }         printf("선생 수 : %d, \t 학생 수  : %d\n", ...

C 언어 구조체의 포인터 멤버 변수

학생11, 학생21은 선생1을 담임선생으로, 학생21, 학생22는 선생2를 담임선생으로 두고 있는 코드이다. #include <stdio.h> struct s_teacher { char name[20]; int age; long number; }; struct s_student { char name[20]; int age; long number; struct s_teacher* pTeacher; //포인터 변수 }; int main() { struct s_student student11 = {"Lee", 20, 4567}; struct s_student student12 = {"Park", 21, 4568}; struct s_student student21 = {"Choi", 20, 4567}; struct s_student student22 = {"Han", 21, 4568}; struct s_teacher teacher1 = {"Kim", 35, 1234}; struct s_teacher teacher2 = {"Nam", 28, 1235}; student11.pTeacher = &teacher1; student12.pTeacher = &teacher1; student21.pTeacher = &teacher2; student22.pTeacher = &teacher2; printf("포인터를 이용한 구조체 변수 접근\n"); printf("학생 %s의 담임교사 이름 : %s\n", student11.name,student11.pTeacher->name); printf("학생 %s의 담임교사 교번 : %ld\n",student12.name,student...

C 언어 중첩구조체 활용과 구조체 포인터를 사용한 직사각형 좌표 출력

s_rectangle 구조체는 중첩구조체로 left_top이라는 s_point 구조체 멤버변수를 가진다. 직사각형의 너비와 너비를 입력받아 나머지 right_top, left_bottom, right_bottom 좌표를 출력해주는 코드이다. #include <stdio.h> struct s_point {         int x;         int y; }; struct s_rectangle {         struct s_point left_top;         int width; //너비         int height; //높이 }; void print_rectangle_info(struct s_rectangle rectangle); void input_rectangle_info(struct s_rectangle *pRectangle); int main() {         struct s_rectangle rectangle = {0};         input_rectangle_info(&rectangle);         print_rectangle_info(rectangle);         return 0; } void input_rectangle_info(struct s_rectangle *pRectangle) {         if(NULL != pRectangle)         {              ...

C 언어 중첩 구조체 선언과 초기화

#include <stdio.h> struct s_teacher { long number; char name[20]; int age; }; struct s_student { sturct s_teacher nested_teachar; long number; char name[20]; int age; int score; }; void print_student_info(struct s_student student); int main() { struct s_student student1 = {{1234,"Kim", 35}, 4567, "Lee", 20, 30 }; struct s_student student2 = {{1234,"Choi"}, 4568, "Lee", 20, 30 }; // 선생 age는 자동으로 0으로 초기화 struct s_student student3 = {1234,"Kim", 35, 4569, "Bak", 21 }; //학생 score는 자동으로 0 으로 초기화 print_student_info(student1); print_student_info(student2); print_student_info(student3); return 0; } void_student_info(struct s_student student) { printf("이름 : %s\t 나이 : %d\t 학번 : %ld\t 점수 : %d\n", student.name, student.age, student.number, student.score); printf("담임선생 이름 : %s\t 담임선생 나이 : %d\t 담임선생 번호 : %ld\n",student.nested_teacher.name, student.nested.age,...

C 언어 구조체 배열 선언과 초기화 방법들

1. 선언과 동시에 0으로 초기화 2. memset() 함수를 이용한 초기화 3. 초기화 목록을 이용한 초기화 4. 반복문을 이용한 초기화 #include <stdio.h> #include <string.h> struct student {         char name[20];         int age;         long number; }; int main() {         //1. 선언과 동시에 0으로 초기화         struct student students[3] = {0};         //2. memset() 함수를 이용한 초기화         struct student students2[3];         memset(students2,0,sizeof(students2));         //3. 초기화 목록을 이용한 초기화         struct student students3[3] = {                 {"kim", 25, 45607},                 {"기리",28,60121315},                 {"Lee",23, 45609}         };         //4. 반...

C 언어 1차원배열 2차원 배열을 활용한 학생관리

학생 수를 입력받아서 국어점수 배열, 영어점수 배열, 수학점수 배열, 총점수 배열과, 학생이름을 담을 배열들을 동적으로 할당한다. 그리고 각각의 점수와 이름들을 입력받고, 각각의 총점과 평균점수를 출력해주고 할당된 메모리를 해제해주는 코드이다. #include <stdio.h> #include <stdlib.h> #include <string.h> int get_student_num(); int alloc_students_scores(int num_student, int** ppscore_kor, int** ppscore_eng, int** ppscore_math                                 , int** ppscore_total); char** alloc_students_name(int num_student); void input_students_info(int num_student, int* pscore_kor, int* pscore_eng, int* pscore_math,                         int* pscore_total,  char **ppstudent_name); void print_avg(int num_student, int* pscore_total, char** ppstudent_name); void print_avgPerSub_totalAvg(int num_student,int* pscore_kor, int* pscore_eng, int* pscore_math, int* pscore_total); void freeMemory(int num_student,int* pscore_ko...

C 언어 함수포인터와 함수포인터배열

함수를 인자로 넘겨주기 위해서 사용된다. callback의 개념과 비슷하다고 보면 될 것 같다.. #include <stdio.h> int add(int value1, int value2); int substract(int value1, int value2); int multiply(int value1, int value2); int (*func_array[3])(int, int) = {add, substract, multiply}; int main() {         int (*pfunc_pointer) (int, int) = NULL;         int result = 0;         int value1 = 0;         int value2 = 0;         int type =0;         printf("첫 번째 값은? " );         scanf("%d", &value1);         printf("두 번째 값은? ");         scanf("%d", &value2);         printf("계산 방식(0: 더하기, 1: 빼기, 2: 곱하기)은 ? ");         scanf("%d", &type);         if(type >= 0 && type <= 2)         {          ...

C 언어 메모리 재할당 realloc() 함수, 초기화 함수 memset() 함수

입력받는 count 변수의 크기가 이전 count보다 값이 크면 배열의 메모리를 count 변수의 크기로 재할당하는 방식의 코드 #include <stdio.h> #include <stdlib.h> #include <string.h> int main() {         int count = 0;         int previousCnt = -1000000000;         int* dynamicIntegerArray = NULL;         int* reallocArray = NULL;         int temp = 0;         do         {                 printf("원소의 개수는 ? (0 이하 값을 입력하면 종료됩니다) ?");                 scanf("%u", &count);                 if(count > 0)                 {                         if(count > previousCnt)                     ...

C 언어 메모리 동적할당 malloc() 함수 메모리해제 free() 함수를 활용

0을 입력하기 전까지 계속해서 학생 수를 받고 학생 당 점수를 입력받아 배열을 관리하며 입력이 끝나면 총점과 평균점수를 출력해주는 코드이다. #include <stdio.h> #include <stdlib.h> void getCountInput(int* count){         printf("학생 수는 ?(0 이하의 수를 입력하면 종료됩니다 :  ");         scanf("%u",count); } void getScoresInput(int* array, int c) {         signed int temp = 0;         for(int i =0; i<c; i++){                 printf("%d 번째 학생의 점수는 ? ",i+1);                 scanf("%u",&temp);                 *(array + i ) = temp;         } } void getSumAndAvg(int* array, int c, int* sum, double* avg) {         for(int i =0; i< c; i++){                 *sum += *(array + i);         }         if( 0 != c)...

C 언어 함수의 활용과 상수 포인터

print_array_reverse는 double형 포인터 변수를 받아 배열의 끝에서 부터 접근해서 출력해주는 함수이다. 여기서 중요한 개념이 있는데, 상수 포인터이다. const double* pArray 는 포인터 변수가 가리키는 변수를 상수화 한다는 의미로 포인터 변수는 다른 주소를 가리킬수 있지만, 가리키고 있는 값을 변경할 수 없게된다. ex) const int* pint_value = &int_value; pint_value = &int_value2;  //가능함!! *pint_value = 10; double* const pArray 처럼 const위치가 바뀐다면 포인터 변수의 상수화로 pArray는 다른 주소를 가리킬수 없게된다. ex)int* const pint_value = &int_value; pint_value = &int_value2; // 오류 발생!! *pint_value = 10;            // 가능함!! #include <stdio.h> void print_array_reverse(const double* pArray, int size); int main() {         double double_array[] = {10.0 , 20.1, 30.2, 40.3};         int size = sizeof(double_array) / sizeof(double);         print_array_reverse(double_array, size);         return 0; } void print_array_reverse(const double* pArray, int size) { ...

C 언어 포인터 변수와 배열 Feat. scanf()

포인터 변수 활용과 사용자 인풋값을 받아 배열에 접근하는 코드 #include <stdio.h> int main() {         int my_int_array[] = {10,20,30,40,50,60,70};         int *pint_value = &my_int_array[0];         int index = 0;         int count = sizeof(my_int_array)/sizeof(int);         printf("인덱스 값은(0~%d)? ",count-1);         scanf("%d", &index);         if ( index >= 0 && index < count ){                 pint_value = pint_value + index;                 printf("인덱스 %d 에 해당하는 값은 %d 입니다. \n", index, *pint_value);         }         else         {                 printf("인덱스 값은 0 보다 크고, %d보다 작아야 합니다. \n", count);         }     ...