Passing Array of Structures to Function C++

Passing an array of structs in C

struct Items
{
char code[10];
char description[30];
int stock;
};

void ReadFile(struct Items items[10])
{
...
}

void xxx()
{
struct Items MyItems[10];
ReadFile(MyItems);
}

This in my compiler works well.
What compiler are you using? What error you got?

Remember to declare your struct before your functions or it will never work.

How to pass an array of struct in a function and change its arguments in C

Your program almost worked. There was a missing bracket to end the for loop in the void initialize(SERVER *s)

Usage of the same name for variable and the name of the structure is confusing.
It is better to avoid it.

The serious problem in the print function was preventing you from seeing the proper results. You used formatting %d twice and supplied only one variable. I guess your intention was to print the serv[2] array. It can be easily done in the for loop.

This is modified program. I changed the initialization function so you can see that elements are properly initialized.

#include <stdio.h>
#include <stdlib.h>

#define Q_LIMT 100

typedef struct servers
{
int id;
int num_in_Q;
int server_status;
}SERVER;

void initialize(SERVER *s);

void initialize(SERVER *s)
{
int i=0,j=0;

for(i=0; i<2; i++) { //i=0; i=1
s[i].id = i; // 0, 1
s[i].num_in_Q = i*i + 1; // 1, 2
s[i].server_status = i+i + 2; // 2, 4
} // the bracket was missing
}

int main()
{
int i;
SERVER serv[2];

initialize(serv);

for(i=0; i<2; i++) {
printf("server[%d].id = %d\n", i, serv[i].id);
printf("server[%d].num_in_Q = %d\n", i, serv[i].num_in_Q);
printf("server[%d].server_status = %d\n\n", i, serv[i].server_status);
}

return 0;
}

OUTPUT:

server[0].id = 0
server[0].num_in_Q = 1
server[0].server_status = 2

server[1].id = 1
server[1].num_in_Q = 2
server[1].server_status = 4

Passing array of structures to function c++

struct MyStruct PassedStruct[]

is mostly an alternative syntax for:

struct MyStruct * PassedStruct

So yes, you will access and modify the original structure.

Just one detail to change, the correct call to to the function is not

myFunction(StructArray[]);

but:

myFunction(StructArray);

Now I will try to explain why I used the word mostly in the above sentence:

I will give some hint at the difference between arrays and pointers, why you shouldn't confuse them (even if I would not say they are unrelated, quite the opposite), and the problem with the above MyStruct PassedStruct[] parameter passing syntax.

This is not for beginners, and C++ standard experts should also avoid reading this (because I don't want to get in some - ISO Standard_ war as I enter ISO undefined behavior territory - a.k.a. forbidden territory).

Let's begin with arrays:

Imagine a simple structure:

struct MyStruct{
int a;
int b;
char c;
};

MyStruct a1[3]; is the declaration of an array whose items are of the above structure type. The most important thing the compiler does when defining an array is to allocate space for it. In our example it reserved space for 3 structs. This reserved space can be on stack or from global memory resources depending where the declaration statement is.

You can also initialize the struct when declaring it like in:

struct MyStruct a1[3] = {{1, 2}, {3, 4}, {5, 6}};

Notice that in this example, I didn't initialize the c field but just a and b. This is allowed. I could also use designator syntax if my compiler supports it like in:

struct MyStruct a1[3] = {{a:1, b:2}, {a:3, b:4}, {a:5, b:6}};

Now, there is another syntax for defining an array using empty square backets like in:

struct MyStruct a2[] = {{1, 2}, {3, 4}, {5, 6}};

The point here is that a2 is a perfectly normal array just like a1. The array size is not implicit, it is given through the initializer: I have three initializers therefore I get an array of three structs.

I could define an uninitialized array of known size with this syntax.
For an uninitialized array of size 3 I would have:

struct MyStruct a2[] = {{},{},{}};

Space is allocated, exactly as with the previous syntax, no pointer involved here.

Let's introduce one pointer:

MyStruct * p1;

This is a simple pointer to a structure of type MyStruct. I can access fields through usual pointer syntax p1->a or (*p1).a. There is also an array flavored syntax to do the same as above p1[0].a. Still the same as above. You just have to remember that p1[0] is a shorthand for (*(p1+0)).

Also remember the rule for pointer arithmetic: adding 1 to a pointer means adding the sizeof the pointed object to the underlying memory address (what you get when you use %p printf format parameter). Pointer arithmetic allows access to successive identical structs. That means that you can access structs by index with p1[0], p1[2], etc.

Boundaries are not checked. What is pointed to in memory is the programmer's responsibility. Yes, I know ISO says differently, but that is what all compilers I ever tried do, so if you know of one that does not, please tell me.

To do anything useful with p1, you have to make it point to some struct of type MyStruct. If you have an array of such structs available like our a1, you can just do p1=a1 and p1 will point to the beginning of the array. In other words you could also have done p1=&a1[0]. It's natural to have a simple syntax available as it's exactly what pointer arithmetic is designed for: accessing arrays of similar objects.

The beauty of that convention is that it allows to completely unify pointer and array access syntax. The difference is only seen by the compiler:

  • when it sees p1[0], it knows it has to fetch the content of a variable whose name is p1 and that it will contain the address of some memory structure.

  • when it sees a1[0], it knows a1 is some constant that should be understood as an address (not something to fetch in memory).

But once the address from p1 or a1 is available the treatment is identical.

A common mistake is to write p1 = &a1. If you do so the compiler will give you some four letter words. Ok, &a1 is also a pointer, but what you get when taking the address of a1 is a pointer to the whole array. That means that if you add 1 to a pointer of this type the actual address will move by steps of 3 structures at once.

The actual type of a pointer of that kind (let's call it p2) would be MyStruct (*p2)[3];. Now you can write p2 = &a1. If you want to access the first struct MyStruct at the beginning of the memory block pointed to by p2 you will have to write somethings like p2[0][0].a or (*p2)[0].a or (*(*p2)).a or (*p2)->a or p2[0]->a.

Thanks to type system and pointer arithmetic all of these are doing exactly the same thing: fetch the address contained in p2, use that address as an array (a known constant address) as explained above.

Now you can understand why pointers and arrays are totally different types that should not be confused as some may say. In plain words pointers are variable that contains an address, arrays are constant addresses. Please don't shoot me C++ Gurus, yes I know that is not the full story and that compilers keep many other informations along with address, size of pointed (addressed ?) object for example.

Now you could wonder why in parameter passing context you can use empty square brackets and it really means pointer. ? No idea. Someone probably thought it looked good.

By the way, at least with gcc, you can also put some value between brackets instead of keeping them empty. It won't make a difference you'll still get a pointer, not an array, and boundaries or type checking are not done. I didn't checked in ISO standard was should be done and if it is required by the standard or if it is a specific behavior.

If you want type checking for boundaries, just use a reference. That may be surprising but this is an area where if you use a reference, the actual type of the parameter is changed from pointer to array (and not from pointer to reference to pointer as may be expected).

MyStruct StructArray[10]; 
  • header: void myFunction(struct MyStruct * PassedStruct)
  • caller: myFunction(StructArray)
  • status: works, you work with a pointer in PassedStruct
  • header: void myFunction(struct MyStruct PassedStruct[])
  • caller: myFunction(StructArray)
  • status: works, you work with a pointer in PassedStruct
  • header: void myFunction(struct MyStruct (& PassedStruct)[10])
  • caller: myFunction(StructArray)
  • status: works, you work with a reference to an array of size 10
  • header: void myFunction(struct MyStruct (& PassedStruct)[11])
  • caller: myFunction(StructArray)
  • status: does not compile, type of array mismatch between prototype and actual parameter
  • header: void myFunction(struct MyStruct PassedStruct[10])
  • caller: myFunction(StructArray)
  • status: works, PassedStruct is a pointer, size provided is ignored
  • header: void myFunction(struct MyStruct PassedStruct[11])
  • caller: myFunction(StructArray)
  • status: works, PassedStruct is a pointer, size provided is ignored

How to pass a structure array to a function in C?

declare any struct, or function before using it, not after

#include <stdio.h>
#include <stddef.h>
#define NKEYS (sizeof keytab/ sizeof (Key))

// define struct first
struct key // create the structure
{ char *word;
int count;
};
typedef struct key Key;

//then the functions that uses it
void traversal(Key *tab, int n);

Key keytab[]={
"auto",0,
"break",0,
"case",0,
"char",0,
"const",0,
"continue",0,
"default",0,
"void",0,
"while",0,
};

int main()
{
traversal(keytab,NKEYS);
return 0;
}

void traversal(Key* tab, int n){
int i;
for (i=0; i<n; i++){
printf("%s\n",tab[i].word);
}
}

passing structure array to function

Given ball *b, b[j] is an element from the elements that b points to. Thus b[j] is not a pointer; it is a struct. Since it is a struct, you use . to refer to members in it.

The definition of b[j] in the C standard is that it is *((b)+(j)). So it takes the pointer b, moves j elements beyond it, and then applies *.

Since * is already applied in b[j], you do not need ->, just ..

How to pass Dynamic array of structures in c++?

It is better to use more safe ways using std::vector or std::shared_ptr. Because it is easy to make a mistake when you use raw pointers.
If you really need to use raw pointer than you need fix your code:

#include <string>
#include <iostream>

// "Data" should be declared before declaration of "function" where "Data" is used as parameter
struct Data {
std::string name;
int age;
std::string dob;
};

void function(Data *family)
{
std::cout << "function called\n";
}

int main()
{
Data *family = new Data[3];
// fill all variables of array by valid data
function(family); // Pass variable "family" but not a type "Data"
delete[] family; // DON'T FORGET TO FREE RESOURCES
return 0; // Return a code to operating system according to program state
}


Related Topics



Leave a reply



Submit