0

I'm trying to count the number of elements in an array as a pointer as the code followed:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int *ptr = (int *) malloc(sizeof(int*));
    for(int i=0; i<8; i++)
        {
            printf("The number: " );
            scanf("%d", &ptr[i]);
        }

    int size = sizeof(ptr)/sizeof(int);
    printf("%d\n", size);
    return 0;
}

I have tried the syntax for an array size = sizeof(ptr)/sizeof(int);but I got the wrong answer which is 1 for all cases. I don't know how to get the correct answer, which is 8 for this case

Hoang Nam
  • 506
  • 2
  • 13
  • You allocate space for a single int pointer not for 8 int. How do you not get segfault in your loop? – Eraklon Mar 10 '20 at 16:40
  • `ptr` is a pointer, so `sizeof ptr` gives the size of the pointer, not the size of the memory block, where it points to. – mch Mar 10 '20 at 16:41
  • 2
    There is no function to get the size of an allocated block after-the-fact. You allocated it, so you know how big it is--you have to save that information yourself. – Lee Daniel Crocker Mar 10 '20 at 16:42
  • @LeeDanielCrocker so there is no way to count the number of elements in the case like this? – Hoang Nam Mar 10 '20 at 16:43
  • There must be a duplicate for this.... the best I can currently find is https://stackoverflow.com/questions/1461432/what-is-array-decaying – Yunnosch Mar 10 '20 at 16:43
  • Does this answer your question? [What is array decaying?](https://stackoverflow.com/questions/1461432/what-is-array-decaying) – Yunnosch Mar 10 '20 at 16:45
  • That's why C functions that operate on arrays take a pointer argument and a size argument--the caller has to know the size, the function cannot determine it at runtime. – Lee Daniel Crocker Mar 10 '20 at 16:53
  • @Eraklon Undefined behavior doesn't guarantee a segfault. It doesn't guarantee *anything*. – Keith Thompson Mar 10 '20 at 16:58
  • The `malloc` call is incorrect. It should be `malloc(sizeof(int) * 8);`. Also, you don't cast the return value of `malloc`. – DarkAtom Mar 10 '20 at 17:16

1 Answers1

0

Unfortunately, you cannot get the size of an array allocated with malloc (because you are actually getting the size of a pointer). You must always store that somwhere else. Since you always allocate 8 elements, why not make it a static array?

#include <stdio.h>

int main()
{
    int arr[8];
    for(int i=0; i<8; i++)
    {
        printf("The number: " );
        scanf("%d", &arr[i]);
    }
    int size = sizeof(arr)/sizeof(int);
    printf("%d\n", size);
    return 0;
}
DarkAtom
  • 2,034
  • 6
  • 17