Skip to content

Commit e08a196

Browse files
[Edit]: C sizeof (#6988)
* [Edit] SQL: DATEDIFF() * Update datediff.md * [Edit] C: `sizeof` * Update content/c/concepts/operators/terms/sizeof/sizeof.md * Update content/c/concepts/operators/terms/sizeof/sizeof.md * Update content/c/concepts/operators/terms/sizeof/sizeof.md ---------
1 parent d144322 commit e08a196

File tree

1 file changed

+156
-17
lines changed
  • content/c/concepts/operators/terms/sizeof

1 file changed

+156
-17
lines changed
Lines changed: 156 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,188 @@
11
---
2-
Title: 'sizeof()'
3-
Description: 'Determines the memory size (in bytes) of a given data type or variable and returns it as an integer.'
2+
Title: 'sizeof'
3+
Description: 'Returns the size in bytes of a data type or variable at compile time.'
44
Subjects:
5-
- 'Code Foundations'
65
- 'Computer Science'
6+
- 'Web Development'
77
Tags:
8-
- 'Arithmetic'
9-
- 'Operators'
8+
- 'Compilation'
109
- 'Data Types'
11-
- 'Variables'
10+
- 'Memory'
11+
- 'Operators'
1212
CatalogContent:
1313
- 'learn-c'
1414
- 'paths/computer-science'
1515
---
1616

17-
In C, the **`sizeof()`** operator returns an integer representing the memory size of a [data type](https://www.codecademy.com/resources/docs/c/data-types) or [variable](https://www.codecademy.com/resources/docs/c/variables) in bytes.
17+
The **`sizeof`** operator is a compile-time unary operator in C that returns the size in bytes of its operand. It calculates the memory space required to store a [data type](https://www.codecademy.com/resources/docs/c/data-types) or variable, returning an unsigned integer value of type `size_t`. The `sizeof` operator is essential for memory management and ensures portability across different platforms where data type sizes may vary.
18+
19+
`sizeof` is widely used in dynamic memory allocation with functions like [`malloc()`](https://www.codecademy.com/resources/docs/c/memory-management/malloc) and [`calloc()`](https://www.codecademy.com/resources/docs/c/memory-management/calloc), array size calculations, and when working with structures and unions. It provides a reliable way to determine memory requirements at compile time, making programs more portable and reducing platform-specific coding issues.
1820

1921
## Syntax
2022

2123
```pseudo
22-
sizeof(input)
24+
sizeof(expression)
25+
sizeof expression
26+
sizeof(type)
2327
```
2428

25-
- `input`: The data type or variable whose memory size is to be calculated.
29+
> **Note:** When using `sizeof` with a type (not a variable), parentheses are mandatory: `sizeof(int)` is valid, but `sizeof int` is not.
30+
31+
**Parameters:**
2632

27-
## Example
33+
- `expression`: Any valid C expression, variable, or array name whose size needs to be determined
34+
- `type`: Any C data type, including primitive types, structures, unions, or arrays
2835

29-
The following example demonstrates the usage of the `sizeof()` operator:
36+
**Return value:**
37+
38+
The `sizeof` operator returns the size in bytes as an unsigned integer value of type `size_t`.
39+
40+
## Example 1: Basic Data Type Sizes
41+
42+
This example demonstrates how to use `sizeof` with basic C data types to determine their memory requirements:
3043

3144
```c
3245
#include <stdio.h>
3346

3447
int main() {
35-
// Calculate the memory size of the 'int' data type
36-
int res = sizeof(int);
37-
38-
// Print the result
39-
printf("Size of int: %d bytes\n", res);
48+
// Display sizes of different data types
49+
printf("Size of char: %zu bytes\n", sizeof(char));
50+
printf("Size of int: %zu bytes\n", sizeof(int));
51+
printf("Size of float: %zu bytes\n", sizeof(float));
52+
printf("Size of double: %zu bytes\n", sizeof(double));
53+
printf("Size of long: %zu bytes\n", sizeof(long));
54+
printf("Size of pointer: %zu bytes\n", sizeof(void*));
4055

4156
return 0;
4257
}
4358
```
4459

45-
The above code produces the following output:
60+
The output of this code will be:
4661

4762
```shell
63+
Size of char: 1 bytes
4864
Size of int: 4 bytes
65+
Size of float: 4 bytes
66+
Size of double: 8 bytes
67+
Size of long: 8 bytes
68+
Size of pointer: 8 bytes
69+
```
70+
71+
This example prints the size of various fundamental data types. The output shows how much memory each type consumes, which helps understand memory usage and choose appropriate data types for specific requirements.
72+
73+
## Example 2: Dynamic Memory Allocation
74+
75+
This example shows how `sizeof` is used in real-world scenarios for dynamic memory allocation, ensuring correct memory allocation regardless of platform:
76+
77+
```c
78+
#include <stdio.h>
79+
#include <stdlib.h>
80+
81+
int main() {
82+
int n = 5;
83+
int *numbers;
84+
85+
// Allocate memory for n integers using sizeof
86+
numbers = (int*)malloc(n * sizeof(int));
87+
88+
// Check if allocation was successful
89+
if (numbers == NULL) {
90+
printf("Memory allocation failed!\n");
91+
return 1;
92+
}
93+
94+
// Initialize the array
95+
for (int i = 0; i < n; i++) {
96+
numbers[i] = (i + 1) * 10;
97+
}
98+
99+
// Display the values and their memory usage
100+
printf("Array values: ");
101+
for (int i = 0; i < n; i++) {
102+
printf("%d ", numbers[i]);
103+
}
104+
printf("\nTotal memory allocated: %zu bytes\n", n * sizeof(int));
105+
106+
// Free the allocated memory
107+
free(numbers);
108+
109+
return 0;
110+
}
111+
```
112+
113+
The output of this code will be:
114+
115+
```shell
116+
Array values: 10 20 30 40 50
117+
Total memory allocated: 20 bytes
49118
```
119+
120+
This example demonstrates the practical use of `sizeof` in dynamic memory allocation. Using `sizeof(int)` ensures the correct amount of memory is allocated regardless of the platform's integer size.
121+
122+
## Example 3: Array Size Calculation
123+
124+
This example illustrates how `sizeof` can be used to calculate the number of elements in an array automatically, which is useful for loop bounds and array processing:
125+
126+
```c
127+
#include <stdio.h>
128+
129+
int main() {
130+
int scores[] = {85, 92, 78, 96, 88, 73, 91};
131+
float temperatures[] = {23.5, 28.1, 19.8, 31.2};
132+
133+
// Calculate number of elements using sizeof
134+
int num_scores = sizeof(scores) / sizeof(scores[0]);
135+
int num_temps = sizeof(temperatures) / sizeof(temperatures[0]);
136+
137+
printf("Scores array:\n");
138+
printf("Total size: %zu bytes\n", sizeof(scores));
139+
printf("Size per element: %zu bytes\n", sizeof(scores[0]));
140+
printf("Number of elements: %d\n", num_scores);
141+
142+
// Process all elements without hardcoding array size
143+
printf("All scores: ");
144+
for (int i = 0; i < num_scores; i++) {
145+
printf("%d ", scores[i]);
146+
}
147+
148+
printf("\n\nTemperatures array:\n");
149+
printf("Number of elements: %d\n", num_temps);
150+
printf("All temperatures: ");
151+
for (int i = 0; i < num_temps; i++) {
152+
printf("%.1f ", temperatures[i]);
153+
}
154+
printf("\n");
155+
156+
return 0;
157+
}
158+
```
159+
160+
The output of this code is:
161+
162+
```shell
163+
Scores array:
164+
Total size: 28 bytes
165+
Size per element: 4 bytes
166+
Number of elements: 7
167+
All scores: 85 92 78 96 88 73 91
168+
169+
Temperatures array:
170+
Number of elements: 4
171+
All temperatures: 23.5 28.1 19.8 31.2
172+
```
173+
174+
This example shows how `sizeof` enables automatic calculation of array lengths, making code more maintainable when array sizes change. The formula `sizeof(array) / sizeof(array[0])` gives the number of elements.
175+
176+
## Frequently Asked Questions
177+
178+
### 1. What is the difference between `strlen()` and `sizeof()`?
179+
180+
`strlen()` counts string characters at runtime, while `sizeof()` returns allocated memory at compile time.
181+
182+
### 2. What is the difference between `sizeof()` and `size()` in C++?
183+
184+
`sizeof()` is a compile-time operator returning bytes, while `size()` is a runtime container method returning element count.
185+
186+
### 3. Can `sizeof()` be used with dynamically allocated memory?
187+
188+
When applied to a pointer, `sizeof()` returns the pointer size, not the allocated memory size.

0 commit comments

Comments
 (0)