SIMPLE malloc & pointer question

Kjartan Pierre Emilsson pierre at rhi.hi.is
Tue Aug 7 20:07:03 AEST 1990


>From article <7206 at helios.TAMU.EDU>, by jdm5548 at diamond.tamu.edu (James Darrell McCauley):
> I have the following code:
> main()
> {
>   int *a,*b;
> 
>   b=(int *)malloc( (unsigned) 4*sizeof(int));
>   b[2]=5;
>   printf("main(): b[2]=%d\n",b[2]);
>   inita(a,b);
>   printf("main(): a[2]=%d\n",a[2]);
> }
> 
> inita (a,b)
> int a[],b[];
> {
>   a=(int *)malloc( (unsigned) 4*sizeof(int));

	...stuff deleted...
> }
> which produces the following output:
> 
	... some output ...

> Segmentation fault (core dumped)
> 

Arguments to function in C are passed by value, which means that a function
cannot alter the content of variables passed to it, but to do so you must pass
the *adress* of the variable you want to change (the pointer to the memory
location of the data you want to change).  A correct version of inita() would
thus be:

		inita(a,b)
		int **a,*b;
		{
			*a = (int *)malloc(4*sizeof(int));
			
		(*a)[2] = 1.0;
		}

Which should be called as inita(&a,b).

-------------------------------------------------------------------------------
Kjartan Pierre Emilsson
Science Institute of The University of Iceland
Dunhaga 3
Reykjavik
Iceland    								email: pierre at krafla.rhi.hi.is



More information about the Comp.lang.c mailing list