Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!samsung!zaphod.mps.ohio-state.edu!rpi!uupsi!sunic!isgate!krafla!pierre From: pierre@rhi.hi.is (Kjartan Pierre Emilsson) Newsgroups: comp.lang.c Subject: Re: SIMPLE malloc & pointer question Message-ID: <1900@krafla.rhi.hi.is> Date: 7 Aug 90 10:07:03 GMT References: <7206@helios.TAMU.EDU> Organization: University of Iceland Lines: 49 From article <7206@helios.TAMU.EDU>, by jdm5548@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@krafla.rhi.hi.is