0

I want to count the total element of a dynamic array. I had search it on another source, and all I got just a static array. How I can count it from a dynamic array? Here is my code :

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int *arr;
    int sz, input, length;

    printf("input size of array:");
    scanf("%d", &sz);

    arr = (int *)malloc(sz * sizeof(int));

    for (int i = 0; i < sz; i++)
    {
        scanf("%d", &input);
    }

    length = sizeof(arr) / sizeof(arr)[0];
    printf("Number of elements present in given array: %d", length);

    return 0;
}

and the output i just get 1

PS D:\Materi Kuliah\1031101 DASPRO\Semester 1\Week-14\Review W6-W7> ./a
input size of array:6
1 
1
2
2
3
3
Number of elements present in given array: 1
a6ret
  • 9
  • 2

1 Answers1

-1

arr is a pointer type, sizeof(arr) is the size of a pointer on your system. To count the number of elements, you can either use the sz variable, or if you are using GCC, use one of the builtin functions for counting the number of elements.

  • well in other case, i have 2 array and the size has depends on user input. but here i want to check the duplicate character, that the algorithm is for (int i = 0; i < sizeChar; i++) { for (int j = i+1; j < sizeChar; j++) { if (karakter[i] == karakter[j]) { duplicate[i] = karakter[i]; } } } i want to put the duplicate character on duplicate[], and then i want to count the element inside it to check how much the duplicate character. if i print the sizeChar, that's will be a different thing – a6ret Dec 16 '20 at 16:45