blog/content/post/2008/07/05/2008-07-05-00000960.md

4.8 KiB
Raw Blame History

title author date wordtwit_post_info categories
ポインタの勉強 kazu634 2008-07-05
O:8:"stdClass":13:{s:6:"manual";b:0;s:11:"tweet_times";i:1;s:5:"delay";i:0;s:7:"enabled";i:1;s:10:"separation";s:2:"60";s:7:"version";s:3:"3.7";s:14:"tweet_template";b:0;s:6:"status";i:2;s:6:"result";a:0:{}s:13:"tweet_counter";i:2;s:13:"tweet_log_ids";a:1:{i:0;i:4117;}s:9:"hash_tags";a:0:{}s:8:"accounts";a:1:{i:0;s:7:"kazu634";}}
C
Programming

関数宣言におけるポインタ

STDINから文字列を読み込んで、それが256文字以内の連続した[A-Za-z0-9]であれば、それを逐一表示する。

以下の二つは同じだよ。

int get_word(char *buf ...)
int get_word(char buf[])

そこら辺に注意して読んでいこう!

/* Include Files */
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
/* ================ */
/* === function === */
/* ================ */
int get_word(char *buf, int buf_size, FILE *fp)
{
int len;
int ch;
/* Go throgh the spaces of the file */
/* getc --> obtains the next input character (if present)
	from the stream pointed at by 
	stream */
/* isalnum --> tests for any character
	for which isalpha(3) or isdigit(3) is true. */
while ((ch = getc(fp)) != EOF && !isalnum(ch));
/* Here, variable ch contains the first character! */
len = ;
do{
/* buf[len] = (the pointer of the array buf[0]) + len */
buf[len] = ch;
len++;
if (len >= buf_size){
fprintf(stderr, "word too long.\n");
exit(1);
}
} while ((ch = getc(fp)) != EOF && isalnum(ch));
/* Add a EOF character at the end. */
buf[len] = '\0';
return len;
}
int main(void)
{
char buf[256];
/* stdinとbufは別物だから切り離して考える */
while (get_word(buf, 256, stdin) != EOF){
printf("<<%s>>\n", buf);
}
}

関数へのポインタ

たとえば、

int func(double d);

というプロトタイプの関数があったとき、関数funcへのポインタを格納するポインタ変数は、以下のように宣言します。

int (*func_p)(double);

そして、以下のように書くと、func_pを経由してfuncを呼び出すことができます。

int (*func_p)(double);
func_p = func;
func_p(0.5);

ちなみに関数へのポインタ変数を格納する配列は

int (*func_p[])(double);