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 :
#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
An array decays to a pointer in function parameters.
sizeof (table)
in the function returns 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:
struct
containing both the array and it's size.