문자열을 입력받아 대문자로 바꿔주는 프로그램이다.
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
int main(void)
{
string s = get_string("s: "); // 입력
string t = s; // t로 문자열복사
t[0] = toupper(t[0]); // 대문자로 변경
printf("%s\n",s); // 대문자로 출력
printf("%s\n",t); // 대문자로 출력
}
t만 대문자로 변경했는데 왜 s도 대문자로 출력되는걸까?
s의 주소값을 t에 할당했기 때문에 포인터 s와 t에 저장된 메모리 주소값이 같다.
그 상태에서 대문자로 변경했기때문에 메모리 주소 안에있는 값도 같은것이다.
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
int main(void)
{
char *s = get_string("s: "); // 입력
char *t = malloc(strlen(s)+1); // malloc(메모리크기) : 메모리 할당 함수
strcpy(t,s); // s의 문자열을 t로 복사
t[0] = toupper(t[0]);
printf("%s\n",s);
printf("%s\n",t);
}
위처럼 malloc() 함수를 이용하여 새로운 메모리 공간을 만들어주면 된다.