array in c++ function code example
Example 1: how to pass an array to a function
#include <stdio.h>
float calculateSum(float age[]);
int main() {
float result, age[] = {23.4, 55, 22.6, 3, 40.5, 18};
result = calculateSum(age);
printf("Result = %.2f", result);
return 0;
}
float calculateSum(float age[]) {
float sum = 0.0;
for (int i = 0; i < 6; ++i) {
sum += age[i];
}
return sum;
}
Example 2: array syntax in c++
int foo [] = { 16, 2, 77, 40, 12071 };
Example 3: array as parameter c++
void myFunction(int param[]) {
.
.
.
}
Example 4: passing array to function c++ pointer
void generateArray(int *a, int si)
{
for (int j = 0; j < si; j++)
a[j] = rand() % 9;
}
int main()
{
const int size=5;
int a[size];
generateArray(a, size);
return 0;
}
Example 5: arrays in c++
#include <iostream>
#include <array>
int main()
{
int example[5];
int* another = new int[5];
delete[] another;
example[0] = 1;
example[1] = 2;
example[2] = 3;
example[3] = 4;
for (int i = 0; i < 5; i++) {
example[i] = 2;
}
int* ptr = example;
example[2] = 5;
*(ptr + 2) = 6;
std::cout << example[2] << std::endl;
*(int*)((char*)ptr + 8) = 8;
std::cout << example[2] << std::endl;
std::array<int,5> stda;
std::cout << stda.size() << std::endl;
std::cin.get();
}
Example 6: array syntax in c++
int bar [5] = { 10, 20, 30 };