0

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?

dasogom
  • 55
  • 5
  • Are you sure you know what `hist[n[i]]++` is doing? – Bathsheba Dec 10 '19 at 08:12
  • 2
    `hist` is not an array, it's a pointer. If the expression `e` has type `T`, `sizeof(e)` is equivalent to `sizeof(T)`. That is, you have `sizeof(int*)/sizeof(int)`. – molbdnilo Dec 10 '19 at 08:12
  • 4
    If all you have is a pointer, it (usually) points to the first element of the array, and that's really all the information you have. There's no way to get the length of the allocated memory from that single pointer, you need to keep track of it yourself in another variable. – Some programmer dude Dec 10 '19 at 08:14
  • [Please see this discussion on why not to cast the return value of malloc() and family in C..](https://stackoverflow.com/q/605845/2173917) – Sourav Ghosh Dec 10 '19 at 08:15
  • 1
    Long before you do `hist[3]++;`, you have to make sure there *is* a `hist[3]`. – David Schwartz Dec 10 '19 at 08:15
  • The length of the histogram is easily known, in case the code is corrected from `int *hist = (int*) malloc(sizeof(int));` to `int *hist = (int*) malloc(sizeofhistogram * sizeof(int));`. You have to know the length of any allocation you ask for anyway. And it obviously is the size of the data value range, which in turn you should already know, at least its theoretical maximum. – Yunnosch Dec 10 '19 at 08:19
  • The line `hist = realloc(hist, sizeof(int));` does nothing. The `realloc` function takes a pointer, and a *new* size. In your code, the new size is the same as the old size, so `realloc` will just return the old pointer. – user3386109 Dec 10 '19 at 08:34
  • *"The output should be 3"* Why? Are you trying to calculate the frequencies of each value in the inputted array and find the maximum? – Bob__ Dec 10 '19 at 08:54

1 Answers1

1

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.

Maxxik CZ
  • 314
  • 2
  • 9