0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C言語で main 関数にコマンドライン引数を渡す方法

0
Posted at

例:

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

int	main(int argc, char **argv)
{
	int	a;
	int	b;

    // argc は引数の個数
	if (argc != 3)
	{
		printf("Usage: %s <num1> <num2>\n", argv[0]);
		return (1);
	}
    
    // atoi:*文字列(char)を整数(int)に変換する関数
	a = atoi(argv[1]);
	b = atoi(argv[2]);
	printf("%d\n", a + b);
	return (0);
}

実行例

$ ./a.out 3 5
8

argc とは:

  • argument count(引数の個数)
  • プログラム実行時に渡された引数の数を表す

例:
./a.out 10 20 のとき, argc = 3

理由:

  1. ./a.out(プログラム名)
  2. 10
  3. 20

char **argv とは

  • argument vector(引数の配列)
  • 各引数を「文字列」として格納した配列

よくある書き方(同じ意味)
int main(int argc, char *argv[]) //これは完全に同じ意味です。

直感的に言うと
./program A B C

はプログラム側では:

argc = 4;

argv[0] = "./program";
argv[1] = "A";
argv[2] = "B";
argv[3] = "C";

argv のポインタ

実行例で考える
./a.out 10 20

全体構造(メモリ図)

argv
 │
 ▼
+-------------------+
| argv[0] | argv[1] | argv[2] | argv[3] |
+-------------------+
    │        │         │         │
    ▼        ▼         ▼         ▼
 "./a.out"  "10"      "20"     NULL
    │        │         │
    ▼        ▼         ▼
  ' . '    '1'       '2'
  ' / '    '0'       '0'
  ' a '    '\0'      '\0'
  ' . '
  ' o '
  ' u '
  ' t '
  '\0'

第1層:argv(ポインタ)
argv → 配列の先頭アドレス

第2層:argv[i](文字列ポインタ)
argv[0] → "./a.out"
argv[1] → "10"
argv[2] → "20"

各要素は:
char *

第3層:文字列本体(char配列)

例えば:

"10" は実際には:

+-----+-----+------+
| '1' | '0' | '\0' |
+-----+-----+------+
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?