C sizeof Operator

Discussions center on the behavior, pitfalls, and best practices of the sizeof operator in C, especially differences between arrays and pointers, compile-time evaluation, and calculating array lengths.

📉 Falling 0.3x Programming Languages
2,124
Comments
20
Years Active
5
Top Authors
#9543
Topic ID

Activity Over Time

2007
8
2008
2
2009
21
2010
41
2011
58
2012
58
2013
81
2014
85
2015
134
2016
191
2017
139
2018
143
2019
139
2020
144
2021
158
2022
171
2023
276
2024
149
2025
115
2026
11

Keywords

GCC CPU OP ycombinator.com lysator.liu FEELS gcc.gnu L1436 FWIW stackoverflow.com sizeof array pointer size type function char compile time pointers operator

Sample Comments

xyzzy2020 Apr 22, 2020 View on HN

How does this not break sizeof ?

rightbyte Sep 13, 2020 View on HN

That mindset doesn't cover sizeof(a) properly.

ori_b Dec 25, 2009 View on HN

Simple rule: Don't use sizeof on pointers. And don't typedef arrays to make them look like simple types.

patrec Apr 23, 2019 View on HN

Downvoters, care to elaborate what you think is wrong with the above? Literally even fortran can do better than size_t len_a = sizeof(a)/sizeof(a[0]); or my_pseudo_foo_array = (foo*) malloc(len * sizeof(foo));

mhh__ Sep 12, 2020 View on HN

You must pass a size_t somewhere, surely? Otherwise you have no idea how long the array is - this is about doing it properly rather than relying on yourself at 9AM to get it right everytime.

tedunangst Jan 18, 2013 View on HN

The sizeof operator begs to differ.

heavenlyblue Oct 16, 2019 View on HN

Does that even work in C when sizeof x[i] > 1?

defen May 15, 2011 View on HN

Working within the "contrived example" framework, it would have made a little more sense if buffer were a pointer rather an array, in which case you wouldn't be able to use "sizeof".

dbaupp Jan 4, 2017 View on HN

They don't, sizeof is a compile-time constant. On a pointer, sizeof() just reports the size of the pointer itself (i.e. 4 or 8 bytes on most modern platforms), not the size of the data to which it points (and sizeof(*pointer) reports the size of the type to which pointer points, it doesn't know anything about how many values of that type are stored). For an array, the length is known statically (i.e. it's in the type), and so the computation can be done at compile time.

exprA Apr 12, 2016 View on HN

C arrays “know” their size. (String literals do too.)