NekoC

猫でもわかるC言語の個人的なまとめ資料

View on GitHub

07_ポインタ

アドレス参照の仕方

書式

printf("%p",&変数);

サンプルコード


#include <stdio.h>
#include <stdlib.h>

int main()
{
	char _char;
	int _int;
	double _double1, _double2;

	printf("_char's Address: %p\n", &_char);
	printf("_int's Address: %p\n", &_int);
	printf("_double1's Address: %p\n", &_double1);
	printf("_double2's Address: %p\n", &_double2);

	system("pause");

	return 0;
}

出力結果


_char's Address: 00AFF87B
_int's Address: 00AFF86C
_double1's Address: 00AFF85C
_double2's Address: 00AFF84C
続行するには何かキーを押してください . . .

解説

大きさ(byte)
char 1
int 1
double 4

ポインタの参照方法

サンプルコード


#include <stdio.h>
#include <stdlib.h>

int main()
{
	int _int;

	/*ポインタの宣言*/
	int* pointer_int;

	/*ポインタにアドレスを格納*/
	pointer_int = &_int;

	printf("適当な整数値を入力してください--- ");
	scanf_s("%d", &_int);
	printf("----------------------------------------\n");
	printf("_int\n");
	printf("\t_int(アドレス): %p\n", &_int);
	printf("\t_int(値): %d\n", _int);
	printf("----------------------------------------\n");
	printf("pointer_int\n");
	printf("\tpointer_int(アドレス): %p\n", pointer_int);
	printf("\tpointer_int(値): %d\n", *pointer_int);
	printf("----------------------------------------\n");

	system("pause");
	return 0;

}

出力結果


適当な整数値を入力してください--- 10
----------------------------------------
_int
        _int(アドレス): 006FFAF4
        _int(値): 10
----------------------------------------
pointer_int
        pointer_int(アドレス): 006FFAF4
        pointer_int(値): 10
----------------------------------------
続行するには何かキーを押してください . . .

ポインタは変数

サンプルコード


#include <stdio.h>
#include <stdlib.h>

int main(){

	int _int1, _int2;
	int* p_int;

	_int1 = 5;
	_int2 = 10;

	p_int = &_int1;

	printf_s("_int1 = %d, _int2 = %d, *p_int = %d\n", _int1, _int2, *p_int);

	p_int = &_int2;

	printf_s("_int1 = %d, _int2 = %d, *p_int = %d\n", _int1, _int2, *p_int);

	system("pause");
	return 0;
}

出力結果


_int1 = 5, _int2 = 10, *p_int = 5
_int1 = 5, _int2 = 10, *p_int = 10
続行するには何かキーを押してください . . .