dasogom
dasogom

Reputation: 55

How to find length of array

I made a histogram and try to find the length of a histogram. But the length of the histogram give me the wrong output. Here is my code first.

int *n = calloc(l,sizeof(int));
for (int i = 0; i < l; i++) {
        scanf("%d", &n[i]);
    }
int *hist = (int*) malloc(sizeof(int));

    for (int i = 0; i<l; i++){
        hist[n[i]]++;
        hist = realloc(hist, sizeof(int));
    }

//length of histogram array
int histlen = sizeof(hist)/sizeof(hist[0]);

printf("legnth : %d\n", histlen);

So

input: 3 3 3 2 2 1

the output should be

length:3

But my code give me

length:2

What is the problem?

Upvotes: 0

Views: 110

Answers (1)

Tekno
Tekno

Reputation: 314

I suggest creating a struct array which will hold the length and the pointer to an array.

struct array {
    int length;
    int* values;
}

Then in your code you can get the length with arr.length and the pointer with arr.values.

Upvotes: 1

Related Questions