How to get the length of an array in C?
C - Size of an array
Code:
int size = sizeof(arr)/sizeof(arr[0]);
Example:
#include <stdio.h>
int main()
{
int arr[] = { 10, 20, 30, 40, 50, 60 };
int size_arra = (arr, sizeof arr / sizeof *arr);
printf("Number of elements in arr[]: %d", size_arra);
}
Output:
6
Note: You can use the sizeof operator to obtain the size (in bytes) of the data type of its operand. The operand may be an actual type specifier (such as int or float), as well as any valid expression. When the operand is a type name, it must be enclosed in parentheses.
Print an array element in C using array size:
C Code:
#include <stddef.h>
#include <stdio.h>
static const int values[] = { 10, 20, 30, 40, 50, 60 };
#define ARRAYSIZE(x) (sizeof x/sizeof x[0])
int main (int argc, char *argv[])
{
size_t i;
printf("Size of the array: %d\n",ARRAYSIZE(values));
for (i = 0; i < ARRAYSIZE(values); i++)
{
printf("%d ", values[i]);
}
return 0;
}
Output:
Size of the array: 6 10 20 30 40 50 60
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join