0

I implemented an insertion sort in C and someone who was helping me told my make something a pointer, as shown in the following line near the end, but why?

size_t size = sizeof( array ) / sizeof( *array ); 

Why is the second one a pointer to array, and what does size_t do?

Cœur
  • 37,241
  • 25
  • 195
  • 267
user3813418
  • 89
  • 1
  • 7

2 Answers2

0

sizeof(array) = size, in bytes, of the entire array;

sizeof(*array) = size, in bytes, of the first item in the array;

As items in a C array are of uniform size, dividing the first by the second gives the number of items in the array.

size_t is an unsigned integer large enough to store the size of any item the computer dan store in memory. So, usually, it's the same as an unsigned int, but it's not guaranteed to be and there's semantic value in it being a different thing.

Tommy
  • 99,986
  • 12
  • 185
  • 204
  • Already edited for `size_t`; `array[0]` would be equivalent. So it's just an arbitrary choice. Arrays are not plain pointers but can be used equivalently to them. – Tommy Jul 09 '14 at 04:09
  • Alright, thanks. So `size_t` could also evaluate to `long long` or `short` or `unsigned long` based on the compiler and architecture? – user3813418 Jul 09 '14 at 04:10
  • Yes. The spec just defines it as "the unsigned integer type of the result of the sizeof operator" and for `sizeof` "The value of the result is implementation-defined, and its type (an unsigned integer type) is size_t". No other constraints are specified. – Tommy Jul 09 '14 at 04:15
0

Why is the second one a pointer to array

Example 1
char a[5];
sizeof(a)=5
sizeof(*a)=1

So, size = 5/1 = 5 // this indicates the no of elements in the array

Example 2
int a[5];
sizeof(a)= 20
sizeof(*a)=4

So, size = 20/4 = 5 // this indicates the no of elements in the array

and what does size_t do?

Read: What is size_t in C?

Community
  • 1
  • 1
brokenfoot
  • 11,083
  • 10
  • 59
  • 80