Trying to pass array of struct pointers to function doIt()
. Looks my way is not correct since I can't get right second array element:
struct c {
int a;
char* b;
};
struct cc {
int a;
c* b;
};
char a[] = "aaa";
char b[] = "bbb";
char e[] = "eee";
c d1 = {1,a};
c d2 = {2,b};
c d3 = { 12,e };
cc g1 = { 123, &d1 };
cc g2 = { 321, &d2 };
cc g3 = { 333, &d3 };
void doIt( c * s)
{
cout << s->b;
s ;
cout << s->b;
}
What is right way to pass array of struct pointers?
CodePudding user response:
Raw arrays in C (and C ) are just pointers. They point to the first element of an array. For example, if you want an array of int
, you would write it like int* array
. If you want an array of struct c
, you would write it like c* array
. If you want an array of pointers to struct c
, you would write it like c** array
.
To access elements, don't use array
, use array[i]
where i
is the index (position) of the element you want to access, 0 being the index of the first element, 1 the second, etc.
So, your code should look like this:
void doIt(c** s)
{
cout << s[0]->b; // s[0] is the first element
cout << s[1]->b; // s[1] is the second
}
Note that in C , it is preferred to use std::vector
instead of raw arrays.
void doIt(std::vector<c*> s)
{
cout << s[0]->b;
cout << s[1]->b;
}
CodePudding user response:
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;
}
}