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言語 Tips

Last updated at Posted at 2025-01-01

配列とポインタは違う

C言語では、関数に配列を渡すときに、配列はポインタとして渡されます。このため、関数内で配列のサイズ(要素数)を直接取得することはできません。配列のサイズを取得するには、配列のサイズ情報を関数の引数として明示的に渡す必要があります。
※ChatGPTより

#include <stdio.h>

void func(char *p)
{
    printf("%ld\n", sizeof(p)); //★8
}

int main()
{
    char s1[100] = "This is array.";
    printf("%ld\n", sizeof(s1)); //★100
    func(s1);
    return 0;
}

s1は配列の先頭アドレスが実体のポインタではなく、配列全体(配列のオブジェクトとして扱う)を示す。
なので、sizeof(s1)で配列のサイズが取得できる。
式で配列オブジェクトを示す場合は、配列の先頭アドレスに変換される。

0
0
2

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?