배열의 element(요소) 개수 구하기

freestyle의 이미지

배열의 element 개수를 구하는 가장 잘 알려진 방법은,

#include <stdio.h>
 
int main(void)
{
        int arr[] = { 1, 2, 3, 4, 5 };
 
 
        printf("count : %d\n", sizeof(arr) / sizeof(arr[0]));
        // or
        // printf("count : %d\n", sizeof(arr) / sizeof(*arr));
 
 
        return 0;
}

일 것입니다(보통 매크로로 제작).

또한 생각해 본 바로는

#include <stdio.h>
 
 
int main(void)
{
        int arr[] = { 1, 2, 3, 4, 5 };
        int *a, *b, *x, *y;
 
 
        a = (int *)(&arr + 1);
        b = (int *)&arr;
        x = arr + 1;
        y = arr;
 
 
        printf("count : %d\n", (a-b)/(x-y));
 
 
        return 0;
}

처럼 나타낼 수 있을 것입니다.

이외에, 다른 방법은 없을까요?
곰곰히 생각해 보고 있는데 더 이상 떠오르지 않네요.

그리고 배열 요소 개수 구하는 함수를 별도로 구현해 함수에 배열을 전달하면
포인터로만 받을 수 있기에
첫 번째의 경우 'sizeof(포인터 변수)'가 되어 원하는 결과를 얻지 못하고,
두 번째 역시 하나의 포인터만 받아서는 참조되는 배열 전체의 크기를 알지 못하게 됩니다.

그래서 제가 생각한 방법은

#include <stdio.h>
 
 
int get_arr_cnt(int *p, int *q);
 
 
int main(void)
{
        int arr[] = { 1, 2, 3, 4, 5 };
 
 
        printf("count : %d\n", get_arr_cnt(arr, (int *)(&arr+1)));
 
 
        return 0;
}
 
 
int get_arr_cnt(int *p, int *q)
{
        return (q - p)/((int *)(p+1) - p);
}

입니다.

count를 직접 전달하지 않고 알아낼 수 있는 방법이 또 뭐가 있을까요?

gurumong의 이미지

두번째 방법은 이상하게 보이는데 잘못된것이 아닌가요?
항상 1이 출력이 될꺼 같은데요

단지 표현만 조금 다를뿐이지 의미상으로는 완전히 같은
a와 x, b와 y인거 같은데요
결국 같은값을 나누니까 결과는 1인거 같은데

freestyle의 이미지

Quote:
두번째 방법은 이상하게 보이는데 잘못된것이 아닌가요?
항상 1이 출력이 될꺼 같은데요

단지 표현만 조금 다를뿐이지 의미상으로는 완전히 같은
a와 x, b와 y인거 같은데요
결국 같은값을 나누니까 결과는 1인거 같은데

cinsk님이 번역하신 CFAQS의 Q 6.12를 보시면

Quote:
다음과 같은 간단한 배열에서:
int a[10];
a에 대한 reference는 “pointer to int”란 타입을 가지며, &a에 대한 reference는
“pointer to array of 10 ints”란 타입을 가집니다.

즉, &arr의 대상체는 배열 전체이며,
+ 연산자의 역할에 의해 '포인터 + 정수 상수'는
해당 포인터가 참조하는 대상체의 크기(sizeof의 결과와 동일) * 정수 상수가 원래의 포인터 값에 더해진 결과가 되므로

&arr+1은 배열의 끝을 가리키는 포인터 상수가 됩니다.
(int*)로 casting한 건 int ** 인데, int *에 구겨넣어 포인터 간의 뺄셈을 하기 위한 것입니다.

----------------------
Go to the U-City

----------------------------------------------------------------------------------------
Don't Feed the Trolls!
----------------------------------------------------------------------------------------

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.