영어로 읽는 코딩

33 [C] static 변수의 사용

Initialization of Pointer Arrays [static에 관한 좋은 내용임]

 

Consider the problem of writing a function month_name(n), which returns a pointer to a character string containing the name of the n-th month. This is an ideal application for an internal static array. month_name contains a private array of character strings, and returns a pointer to the proper one when called. This section shows how that array of names is initialized.

 

The syntax is similar to previous initializations:

 

/* month_name: return name of n-th month */
char *month_name(int n)
{
    static char *name[] = {
		”Illegal month ”,
		”January” , ”February” , !’March” ,
		”April” , ”May” , ”June ” ,
		”July” , ”August” , ”September” ,
		” October ”, ” November ”, ”December”
	};
	return ( n < 1 || n > 12 )  ? name [ 0 ] : name [ n ] ;
}

 

The declaration of name is an array of character pointers. The initializer is a list of character strings; each is assigned to the corresponding position in the array. The characters of the i-th string are placed somewhere, and a pointer to them is stored in name[ i ]. Since the size of the array name is not specified, the compiler counts the initializers and fills in the correct number.

 

[The C Programming Language p.113]

댓글

댓글 본문
버전 관리
Yoo Moon Il
현재 버전
선택 버전
graphittie 자세히 보기