This article explains by example how to pass an array of structures to a function using pointers.
The problem.
We have an array of structures struct st sdata s[100];
Each one of these 100 structures are of st type.
and we will pass this array of structures to a function using pointers.
The strategy for the solution.
1) we make an array of pointers writing struct st ((* sdata apt[100] )) ;
2) Each one of these 100 pointers points to one member of the array s[100].
we write:
for(i=0;i<100;i++)
{
apt[i]= & s[i];
}
3) The function that we will call is : void mf ( ms ( ( sdata *(*pt )[100])) )
with : typedef struct st ms;
4) we pass the array of structures to the function,calling it, writing:
mf (& apt);
Important points to remember to understand the C code.
1) pt=& apt
2)*pt=apt =& apt[0]
3)*pt+i=& apt[i]
4) *(*pt+i)= apt[i]
5)**(*pt+i)= s[i]
The examlpe C code includes for comparison both methods of catching memberes of a structure by pointer: using (*). or ->
The C code is here the result
Exercise 1 : Having an array, say struct st sdata s[100] we know that s=&s[0].
So, s+i =&s[i].
Having this in mind we have now pointers to search the elements of the array via pointers.
Rewrite the above program without using an intermediate array of pointers [steps 1). and 2). above].
You have to replace the expression **(*pt+i). with *(*pt+i). and *(*pt+i)-> with
(*pt+i)-> , the called function will be void mf( ms(*pt)[100] ) and to call this you write
mf(&s);
The C code is here the result
Exercise 2 : Rerwite the program of exercise 1 using a pointer pt pointing to a structure of st type. You have to replace *(*pt+i) with * (pt+i) and (*pt+i) with (pt+i). The called function will be void mf ( ms *pt ) and to call it you write mf (s); and not mf (&s); because s is a pointer to a structure of st type already!
All these are also true and about strings. Calling a string named string you have not to write &string but string simply. The name of a string is a pointer to its first character!
The C code The result
Important note
Giving the definition of a pointer we have: "Pointer is an object that is equal to an address that can be stored and changed".
Under this definition it is not exact to say that the name of an array or string or structure is a pointer.Of course they are equal with an address but this address can't be stored or changed.
We can't change the address of an array, of a string ,of a stucture.
Having a pointer p and an array s we can write p=s but we can't write s=p.
Names of arrays, stirngs and structures can't be at the left side of an assigment operator, to be lvalues.
So, always remember: An object that is equal to an address it is not sure that it is a pointer..
|