LoginSignup
0
0

More than 5 years have passed since last update.

[C言語]関数と配列周りでハマりそうなポインタの仕様

Last updated at Posted at 2018-12-28

C言語、ポインタと配列周りでハマりそうな仕様

#include <stdio.h>

void funcA(int x){
 // スコープ外で値代入
 x = 10;
}

void funcB(int* x){
 // 間接参照で値を代入
 x[0] = 30;
}

// funcC(int* x){
// 関数の引数に配列を指定すると↑のように勝手にint*型宣言される
void funcC(int x[3]){
 // なのでパッと見スコープ外に見えるが、間接参照されている
 x[0] = 50;
}

int main(void){
 int a = 5;
 funcA(a); // 値渡し
 printf("funcA(): a=%d\n", a); // 変数aの値は5のまま

 int b[3];
 b[0] = 20;
 funcB(&b[0]); // ポインタ渡し(配列は先頭ポインタを渡す)
 printf("funcB(): b[0]=%d\n", b[0]); // 配列b[0]の値は20から30に変わる

 int c[3];
 c[0] = 40;
 // 下記のように&と[]を省略すると、勝手に配列の先頭ポインタを渡している扱いになる
 funcC(c); // ポインタ渡しになる ※「funcC(&c[0])」 と同等
 printf("funcC(): c[0]=%d\n", *c); // 配列c[0]の値は40から50に変わる

 printf("---------\n");
 printf("funcA(): a=%d, funcB(): b[0]=%d, funcC(): c[0]=%d", a, b[0], *c);
 // b[0]と*bは同じ意味
 // b[整数]と*(b+整数)は同じ意味

 return 0;
}

結果

funcA(): a=5
funcB(): b[0]=30
funcC(): c[0]=50
---------
funcA(): a=5, funcB(): b[0]=30, funcC(): c[0]=50
0
0
4

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
0
0