www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/08/02/07:00:38

From: "Alberto Chessa" <achessa AT fiar DOT finmeccanica DOT it>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Passing parameters to a function
Date: 30 Jul 1998 07:29:22 GMT
Organization: TIN
Message-ID: <01bdbb8c$0ed38280$92c809c0@chessa>
References: <35be3ee4 DOT 5431736 AT news DOT cww DOT de>
NNTP-Posting-Host: a-mi48-39.tin.it
Lines: 56
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

Georg Gretz <newjack AT gmx DOT de> wrote in article
<35be3ee4 DOT 5431736 AT news DOT cww DOT de>...
> 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:
> 

When You make a reference to the name of an array, You make a reference to
a pointer to the array:  array_name[n] is  *(array_name+n), so array_name
is simple &array_name[0], that is the address of the array.
The difference between declaring a "pointer to" and an array is that the
array declaration allocated memory a create a const symbol with the name of
the array holding the address of the array elements, while the pointer is
simple a pointer. It has no memory associated and can be modified.
Note that "int **x" and "int x[n][m]" (a pointer to a pointer and a matrix)
are not the same, while "int **x" and "int *x[n]" can be managed in the
same way.

> typedef   struct { int a,b,c,d } t_struct[100];
> 
> test(/* ??? */) /* Here I want to get a pointer that points at the
>                                array above. */

test(t_struct t)	

>   {
>     /* How can I modify the a,b,c,d? */

       t[n].a=...;

>   }
> 
> main()
> {
>   t_struct testarray;
>   test(/* ??? */); /* How can I pass the pointer of testarray to the
>                                   function? */

    test(testarray); // the name of an array is a "t_struct *const
testarray"
> }
> 
> 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.
> 

C pass parameters "by value" by default, the original variable cannot be
modified. It's also true for array, since an array name is a pointer to the
array. The parameter is the array name, not the array. You can change the
object pointed by, but You cannot change the array pointer. To pass an
array "by value" You have to make it a struct:
  typedef struct { t_struct t} teststrcut_t;
Of course, this require sizeof(teststruct_t) bytes to be pushed onto the
stack...

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019