If you want to pass array to a function you need also pass length of this array:
#include <iostream>
#include <vector>
struct c {
int a;
char* b = nullptr;
size_t size = 0;
};
void doIt(c* all, size_t length);
int main()
{
char a[] = "aaa";
const size_t sizeOfA = sizeof(a)/sizeof(a[0]);
char b[] = "bbb";
const size_t sizeOfB = sizeof(b)/sizeof(b[0]);
char e[] = "eee";
const size_t sizeOfE = sizeof(e)/sizeof(e[0]);
c d1 {1, a, sizeOfA};
c d2 {2, b, sizeOfB};
c d3 {12, e, sizeOfE};
c all[] = {d1, d2, d3};
const size_t length = sizeof(all)/sizeof(all[0]);
doIt(all, length);
return 0;
}
void doIt(c* all, size_t length)
{
if (!all)
{
std::cerr << "Pointer to array is null" << std::endl;
}
for (size_t i = 0; i < length; ++i)
{
for (size_t j = 0; j < all[i].size; ++j)
{
std::cout << all[i].b[j];
}
std::cout << std::endl;
}
}
You can use std::vector
. So, you don't need to use adittional argument (length of the vector):
#include <iostream>
#include <vector>
#include <string>
struct c {
int a;
std::string b;
};
void doIt(const std::vector<c>& myVector);
int main()
{
std::vector<c> myVector;
myVector.emplace_back(1, "aaa");
myVector.emplace_back(2, "bbb");
myVector.emplace_back(12, "eee");
doIt(myVector);
return 0;
}
void doIt(const std::vector<c>& myVector)
{
for (size_t i = 0; i < myVector.size(); ++i)
{
std::cout << myVector[i].b << std::endl;
}
}