こう書きます。
C
1#include <stdio.h>
2
3int main(void) {
4 int i;
5 char a[][5] = {"A", "B", "C"};
6 char *p[] = {"A", "B", "C"};
7
8 printf("sizeof(a)=%zu, sizeof(a[0])=%zu\n", sizeof(a), sizeof(a[0]));
9
10 /* (sizeof(a) / sizeof(a[0])) と書くことが多いが、()が多いのでこの例では除去している */
11 for (i = 0; i < (sizeof a / sizeof a[0]); i++) {
12 printf("a[%d] = %s\n",i, a[i]);
13 }
14
15 printf("sizeof(p)=%zu, sizeof(p[0])=%zu\n", sizeof(p), sizeof(p[0]));
16
17 for (i = 0; i < (sizeof p / sizeof p[0]); i++) {
18 printf("p[%d] = %s\n",i,p[i]);
19 }
20
21 int n = 0;
22 for (i = 0; i < sizeof(p) / sizeof(p[0]); i++) {
23 n++;
24 }
25
26 printf("n=%d\n",n);
27
28 for (i = 0; i < n; i++) {
29 printf("p[%d] = %s\n",i, p[i]);
30 }
31
32 return 0;
33}
実行結果です。
terminal
1$ gcc --version
2gcc (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0
3Copyright (C) 2017 Free Software Foundation, Inc.
4This is free software; see the source for copying conditions. There is NO
5warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
6
7$ gcc -Wall t14.c
8$ ./a.out
9sizeof(a)=15, sizeof(a[0])=5
10a[0] = A
11a[1] = B
12a[2] = C
13sizeof(p)=24, sizeof(p[0])=8
14p[0] = A
15p[1] = B
16p[2] = C
17n=3
18p[0] = A
19p[1] = B
20p[2] = C
21$
22
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/12/15 04:38
退会済みユーザー
2020/12/16 01:15