SIMPLE malloc & pointer question
Richard Tobin
richard at aiai.ed.ac.uk
Wed Aug 8 00:22:03 AEST 1990
In article <7206 at helios.TAMU.EDU> jdm5548 at diamond.tamu.edu (James Darrell McCauley) writes:
> inita(a,b);
> printf("main(): a[2]=%d\n",a[2]);
>inita (a,b)
>int a[],b[];
>{
> a=(int *)malloc( (unsigned) 4*sizeof(int));
> a[2]=3;
Arguments in C are passed by value, not reference. inita() gets a copy
of main()'s variable "a", so when inita() returns the value in main()
is unchanged.
If you want to modify a variable in the parent procedure, you should
pass a pointer to it:
inita(&a,b);
and declare the argument appropriately:
int **a; /* a is a pointer to a pointer to integers */
and assign to what the argument points to, not the argument itself
(*a)=(int *)malloc( (unsigned) 4*sizeof(int));
(*a)[2]=3;
-- Richard
--
Richard Tobin, JANET: R.Tobin at uk.ac.ed
AI Applications Institute, ARPA: R.Tobin%uk.ac.ed at nsfnet-relay.ac.uk
Edinburgh University. UUCP: ...!ukc!ed.ac.uk!R.Tobin
More information about the Comp.lang.c
mailing list