Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sizeof(element) change between main and other function

I’m new in C and I’m trying to make an algorithm with bubble sort. It’s not so hard but I don’t understand why my sizeof() of a table change between my main function and another function.

Indeed, I have a table with 5 elements, so my sizeof(), because for me int is equal to four bytes, is equal to 20. However, when I put my table into a function, with a pointer, my sizeof gets 8. In my opinion, it’s the same table so I don’t understand why.

Here my code :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

void bubble_sort(int* table) {
    printf("Size of table in bubble sort function : %d\n", sizeof(table));
    int permutation = 1;
    int number = 0;
    while(permutation != 0) {
        permutation = 0;
        for (int i = 0; i < sizeof(table)/sizeof(int); i++) {
            if (table[i] > table[i+1]) {
                    number = table[i];
                    table[i] = table[i+1];
                    table[i+1] = number;
                    permutation++;
            }
        }
    }
}

int main() {
    int table[5] = {3, 20, 12, 4, 21};
    printf("Size of table in main function : %d\n", sizeof(table));
    bubble_sort(table);
}

And I got this :

Size of table in main function : 20
Size of table in bubble sort function : 8

>Solution :

An array decays to a pointer in function parameters.

sizeof (table) in the function gives the size of the pointer, not the size of the array it points to. You can’t determine the size of an array from a decayed pointer value of the array.

There might be a trick or two, but I do not know of any standard way to do so.
You could instead:

  • Pass in the size as a separate parameter.
  • Pass a pointer to a struct containing both the array and it’s size.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading