How to determine the length of an array in C
C does not provide a built-in method to obtainLarge numbers. You must do some work first.
I want to mention the easiest way: first save the length of the array in a variable. Sometimes, a simple solution is the most effective method.
Instead of defining the array like this:
int prices[5] = { 1, 2, 3, 4, 5 };
You use a variable as the size:
const int SIZE = 5;
int prices[SIZE] = { 1, 2, 3, 4, 5 };
So, for example, if you need to use a loop to iterate the array, you can useSIZE
Changing:
for (int i = 0; i < SIZE; i++) {
printf("%u\n", prices[i]);
}
The easiest way to get the length value of an array is to usesizeof
operator.
First, you need to determine the size of the array. Then you need to divide it by the size of an element. It works because each item in the array has the same type and the same size.
example:
int prices[5] = { 1, 2, 3, 4, 5 };
int size = sizeof prices / sizeof prices[0];
printf("%u", size); /* 5 */
instead:
int size = sizeof prices / sizeof prices[0];
You can also use:
int size = sizeof prices / sizeof *prices;
AspointerPoints to the first item of the string.
Download mine for freeC manual
More clang tutorials:
- Introduction to C programming language
- C variables and types
- C constant
- C operator
- C conditional
- How to use loops in C
- Introduction to C arrays
- How to determine the length of an array in C
- Introduction to C strings
- How to find the length of a string in C
- C pointer introduction
- Iterate over the array in C
- Boolean in C
- Introduction to C functions
- How to use NULL in C
- Basic I/O concepts in C language
- Double quotes and single quotes in C
- How to return a string from a C function
- How to solve the implicit declaration library function warning in C language
- How to check character value in C
- How to use `printf()` to print percent characters in C language
- C conversion specifiers and modifiers
- How to access command line parameters in C
- Range of variables in C
- Can functions be nested in C?
- Static variables in C
- C global variables
- Typedef keyword in C language
- C enumeration type
- C structure
- C header file
- C preprocessor