문자열의 배열

앞에서 다차원 배열을 사용했듯이, 문자열의 배열도 만들 수 있다.

const char* mythings[5] =
	{
		"Dancing in the rain",
		"Counting apples",
		"Watching movies with friends",
		"Writing sad letters",
		"Studying the C language",
	};

	char yourtings[5][40] =
	{
		"Studying the C++ language",
		"Eating",
		"Watching Netflix",
		"Walking around till dark",
		"Deleting spam emails"
	};

포인터 변수 mythings와 문자열 배열 yourtings 를 각각 선언했다.

다음으로 포인터 변수가 가리키는 첫 문장과 문자열 배열이 담고 있는 첫 문장을 따로 포인터변수 temp1temp2에 할당해준다.

const char* temp1 = "Dancing in the rain";
const char* temp2 = "Studying the C++ language";

printf("%s %u %u\\n", mythings[0], (unsigned)mythings[0], (unsigned)temp1);
printf("%s %u %u\\n", yourthings[0], (unsigned)yourthings[0], (unsigned)temp2);

출력해보면, 포인터 변수는 같은 주소가 나오고, 문자열 배열은 같은 문장이지만 다른 주소가 나온다.

Untitled

그 이유는 포인터가 가리키는 문자열은 리터럴 상수로 TEXT Segment에 위치해있는걸 그냥 가리키고만 있기 때문이고, 배열들은 본인들만의 메모리 공간에 문자열들을 복사해서 갖고 있기 때문임.

문자열을 가리키는 포인터와 문자열배열을 출력하는 코드이다.

printf("%-30s %-30s\\n", "my things:", "yourthings:");
for (int i = 0; i < 5; i++)
{
	printf("%-30s %-30s\\n", mythings[i], yourthings[i]);
}

여기서 -30 이라는 printf()의 포맷은 출력할때 30자리의 공간을 확보하고, 그 공간안에서 왼쪽 정렬-한다는 의미이다.

이런 결과가 나온다.

Untitled

이번엔 mythingsyourthings의 크기를 출력해보았다.

printf("\\nsize fo mythings : %zd, sizeof yourthings : %zd\\n",
sizeof(mythings), sizeof(yourthings));