2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【C++】基礎を学ぶ⑭~ポインタ~

Last updated at Posted at 2022-07-11

ポインタ

ポインタとは、メモリのアドレス(番地)を指し示す仕組みである
ポインタメモリを直接扱うために用いられる

メモリ

コンピュータに取り付けられている記憶装置
プログラムで書いた変数や関数などはメモリに保存される

ポインタを使うメリット

  • コードをシンプルに書くことができる
  • 効率よく動作するプログラムを書くことができる

ポインタの構文

操作 構文
ポインタの宣言 型 *ポインタ;
変数のアドレスを取得 &変数
ポインタのさす先へのアクセス *ポインタ

ポインタを使ったプログラム

#include <iostream>
using namespace std;
 
int main() {
  int x = 1; // int型の変数xを1で初期化
  int *p;    // ポインタpの宣言
  p = &x;    // xのアドレスで初期化
  *p = 2;    // ポインタが指すメモリへの書き込み
  cout << x << endl;
 
  int y;
  y = *p;  // ポインタ経由でxの値を読み取る
  cout << y << endl;
}
2
2

ポインタで別の関数から値を操作する

#include <iostream>
using namespace std;
 
void f(int *ref) {
  *ref = 2;
}

int main() {
  int x = 1;
  f(&x); // xのアドレスを引数に設定
  cout << x << endl;
}
2

次の記事

【C++】基礎を学ぶ⑮~構造体~

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?