8-2. 関数とポインタ

ポインタ
[文法]
・形式 アドレス演算子&:
&識別子


&a aのアドレスを得る

・形式 間接演算子*;
*識別子

int *a; aはintへのポインタ
space.gif
line.gif
space.gif
#include<stdio.h>

int main(void){
space.gif int x=1; int y=2;
space.gif int *ip;
space.gif printf("xのアドレス:%p\n", &x);
space.gif ip = &x;
space.gif printf("x:%p\n", *ip);
space.gif y=*ip;
space.gif *ip = 0;
space.gif printf("x:%d, y:%d", x, y);
space.gif return 0;
}
space.gif
line.gif
space.gif
ポインタを引き数とする関数
例. 前回の関数Subssをポインタを引き数とする関数に変更する
ssflow.GIF
subss.gif
space.gif
line.gif
space.gif
#include<stdio.h>

void Subss(int *z, int *x, int *y){
space.gif int a = *x; int b = *y;
space.gif *z = a*a + b*b;
}

int main(void){
space.gifint a, b, c, d, e, f, g;
space.gifprintf("Input b, c, e, f");
space.gifscanf("%d %d %d %d", &b, &c, &e, &f);
space.gif Subss( &a, &b, &c );
space.gif Subss( &d, &e, &f );
space.gifg = a+d;
space.gifprintf("g=%d\n", g);
}
space.gif
line.gif
space.gif
文字列
文字列は、文字の並びを表現する
末尾は、ナル文字 '\0'である

例。文字列の初期化と表示
char str[] = { 'A', 'B', 'C', '\n'}
char str[] = "ABC"

printf("%s", str); /* 表示 */

space.gif
line.gif
space.gif
#include<stdio.h>

int main(void){
space.gif char name[50];
space.gif printf("Name:");
space.gif scanf("%s", name);

space.gif printf("Your name is %s", name);
space.gif return 0;
}
space.gif
line.gif
space.gif
文字列(配列)と関数
int a[5] = { 0, 1, 2, 3, 4}
int *pa;
pa = &a[0]
a:
0 1 2 3 4

space.gif
line.gif
space.gif
#include<stdio.h>

int str_len(char *s){
space.gif int n;
space.gif for(n=0; *s='\0'; s++) n++;
space.gif return n
}
int main(void){
space.gif int n;
space.gif char str[50];
space.gif scanf("%s", str);

space.gif n = str_len(str);
space.gif printf("String Length = %d", n);
space.gif return 0;
}