강좌 : 부스트캠프 모두를 위한 컴퓨터과학(cs50 2019)
get_string
: 호출될때마다 포인터를 반환
#include<cs50.h>
#include<stdio.h>
#include<string.h>
int main(void)
{
string s = get_string("s: ");
string t = get_string("t: ");
if(strcmp(s,t) == 0)
{
printf("same\n");
}
else
{
printf("different\n");
}
}
사용자에게 입력값을 받아 첫글자를 대문자로 출력하기
#include<cs50.h>
#include<ctype.h> //toupper을 사용하기 위한 헤더파일
#include<stdio.h>
int main(void)
{
string s = get_string("s: ");
// s라는 변수에 문자열이 아닌 그 문자열이 있는 메모리의 주소가 저장
string t = s;
// 따라서 t도 동일한 주소를 가르킨다
t[0] = toupper(t[0]); // 동일한 주소이므로 t를 통한 수정은 s에도 반영
printf("s: %s\n",s);
printf("t: %s\n",t);
// s와 t 동일하게 출력
}
malloc
: 정해진 크기만틈 메모리를 할당하는 함수
#include<cs50.h>
#include<ctype.h>
#include<stdio.h>
#include<string.h> //strlen을 사용하기 위한 헤더파일
#include<stdlib.h> // malloc를 사용하기 위한 헤더파일
int main(void)
{
string s = get_string("s: ");
string t = malloc(strlen(s)+1); // 메모리 할당함수를 사용해 t 정의
// 문자열길이 + 널종단문자
for(int i = 0, n = strlen(s); i < n + 1; i++)
{
t[i] = s[i]; // for 함수를 이용해 널종단문자까지 카피
}
t[0] = toupper(t[0]);
printf("s: %s\n",s);
printf("t: %s\n",t);
}
strcpy
: 문자열 카피 함수
#include<cs50.h>
#include<ctype.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(void)
{
string s = get_string("s: ");
string t = malloc(strlen(s)+1);
strcpy(t, s); // for 함수대신 간단히 문자열 카피
t[0] = toupper(t[0]);
printf("s: %s\n",s);
printf("t: %s\n",t);
}
malloc
함수를 이용하여 메모리를 할당한 후에는 free
라는 함수를 이용하여 메모리를 해제해야한다$ help50 valgrind ./파일명
명령어를 사용하면 파일에 대한 valgrind 검사 내용을 확인할 수 있다swap
: 정수를 입력받아 그 값을 바꾸는 일을 수행
메모리 | 저장값 |
---|---|
machine code | 컴파일된 바이너리 |
globals | 프로그램 안에서 저장된 전역변수 |
heap ↓ 쌓이면서 저장 ↑ stack | malloc으로 할당된 메모리의 데이터 프로그램 내의 함수와 관련된 것들 |
// 잘못된 코드
#include <stdio.h>
void swap(int a, int b);
int main(void)
{
int x = 1;
int y = 2;
printf("x is %i, y is %i\n", x,y);
swap(x,y);
printf("x is %i, y is %i\n", x,y); // 위와 같은 결과가 출력된다
}
void swap(int a, int b)
{
int tmp = a;
a = b;
b = tmp;
}
// 올바른 코드
#include <stdio.h>
void swap(int *a, int *b);
int main(void)
{
int x = 1;
int y = 2;
printf("x is %i, y is %i\n", x,y);
swap(&x, &y); // x와 y의 주소를 불러온다
printf("x is %i, y is %i\n", x,y); // x와 y값이 바뀐 결과가 출력된다
}
void swap(int *a, int *b) // 불러온 주소로 a와 b가 간다
{
int tmp = *a;
*a = *b;
*b = tmp;
}