Computer >> 컴퓨터 >  >> 프로그램 작성 >> C 프로그래밍

sizeof를 사용하지 않고 C/C++에서 배열 크기 찾기

<시간/>

이 프로그램에서는 sizeof를 사용하지 않고 C/C++에서 배열의 크기를 찾습니다.

알고리즘

Begin
   Initialize the elements of the array.
   &a => This is the pointer to array which points at the same memory address as a.
   &a + 1 => It points at the address after the end of the array.
   *(a+1) => Dereferencing to *(&a + 1) gives the address after the end of the last element.
   *(a+1)-a => Subtract the pointer to the first element to get the length of the array.
   Print the size.
End.

예시 코드

#include <iostream>
using namespace std;
int main() {
   int a[] = {6,7,5,3,1,4,2,10,9};
   int s = *(&a + 1) - a;
   cout << "Number of elements in array is "<< s;
}
입니다.

출력

Number of elements in array is 9