less than 1 minute read

main

#include <bits/stdc++.h> 
#define ll long long
using namespace std;

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int a[] = { 1,2,3,4,5 };
    int size = sizeof(a) / sizeof(a[0]);
    cout << sizeof(a) << " " << sizeof(a[0]) << " " << size;
    //20 4 5

    return 0;
}

main에서의 a[]에 관한 사이즈 입니다.

함수에서

#include <bits/stdc++.h> 
#define ll long long
using namespace std;

int sumArr(int arr[]) // == int* arr
{
    int sum = 0;
    int size = sizeof(arr) / sizeof(arr[0]);
    printf("%d, %d, %d", sizeof(arr), sizeof(arr[0]), size);
    //4 4 1
    return 0;
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int a[] = { 1,2,3,4,5 };
    cout << sizeof(*a) << "\n";
    //4
    sumArr(a);
    

    return 0;
}

함수에서 sizeof(arr)가 4가 나오는 이유는 a[0]의 주소를 넘겨주기 때문입니다. shot2

EX

#include <bits/stdc++.h> 
#define ll long long
using namespace std;

int sumArr(int arr[],int size)
{
    int sum = 0;
    for (int i = 0; i < size; i++)
        sum += arr[i]; // == *(arr + i);
    return sum;
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int a[] = { 1,2,3,4,5 };
    int size = sizeof(a) / sizeof(a[0]);
    cout << sumArr(a, size);
    //15
    

    return 0;
}

함수에 배열을 전달하면 그 배열의 베이스 주소를 전달하는걸 알 수 있습니다.

Leave a comment