There are two methods to get the size of an array in C language.
/*
Get the array size in C language
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
// traverse using pointer
void displayArr1(int * array, int size,int tsize) {
printf("%d ",size);
printf("%d ", tsize);
for(int i = 0; i < size; i++) {
*array += tsize;
printf("%d ", *(array++));
}
printf("\n");
}
// traverse normally
void displayArr2(int array[], int size,int tsize) {
// int size = sizeof(array) / sizeof(int);//The array size cannot be obtained correctly in a subfunction
for(int i = 0; i < size; i++) {
array[i] += tsize;
printf("%d ", array[i]);
}
printf("\n");
}
int main(int argc, char *argv[]) {
int arr[] = {1,2,3,45,67};
// displayArr1(arr, sizeof(arr) /sizeof(arr[0]) , sizeof(arr[0]));
displayArr1(arr, sizeof(arr)/sizeof(int) , sizeof(int));
return 0;
}Source:www.lautturi.comExample of getting array size using strlen:
/*
Get the array size in C language
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
void displayArr(char array[], int size) {
for(int i = 0; i < size; i++) {
printf("%c ", array[i]);
}
printf("\n");
}
int main(int argc, char *argv[]) {
char arr[] = {'1','2','a','b','e'};
int size = strlen(arr);
displayArr(arr, size);
return 0;
}