Mail Archives: djgpp/1998/07/30/07:30:21
> Hello all,
>
> 1. could anybody tell me, how may I pass a pointer of an array as a
> paramater to a function? A small example for a better understanding:
>
> typedef
> struct { int a,b,c,d } t_struct[100];
>
test(t_struct theArray)
> /* Here I want to get a pointer that points at the
> array above. */
> {
>
theArray[0].a = 0;theArray[1].b = 2;/* it modifies the a,b,c,d? */
> }
>
> main()
> {
> t_struct testarray;
test(testarray ); /* for t_struct is an array type it is allready a
pointer*/
/* theArray[0].a is 0 theArray[1].b is 2 */
> }
>
> 2. How can I pass a parameter to the function by "call by value"? I
> don't want that the function modifies my main-variables.
>
Each parameter you pass in c is allwas "by value" (in c there is no "by
reference"). If you pass a pointer to a function in any way the pointer
will be unchanged by the called function.
To preserve the area where the pointer is pointing to from beeing
changed you might define something like:
const char * DontChangeTheText;
In c++ in principle is's the same, despites there is an explicit way to
give an implicit pointer.
void MyFunc( int & looksLikeByRef ) {
looksLikeByRef++;
}
void main() {
int i = 1;
MyFunc( i );
/* now i is 2;* /
}
what the int& is telling the compile is:
- Dont take the parameter in the function call, but take it's adress.
(semiaddress)
- Treat this adress inside the fuction like *(semiaddress)
So it's effectively working like a reference.
All other ways are by value!
Uwe
- Raw text -