SIMPLE malloc & pointer question

Pat Broderick ptb at ittc.wec.com
Thu Aug 9 01:04:16 AEST 1990


In article <7206 at helios.TAMU.EDU>, jdm5548 at diamond.tamu.edu (James Darrell McCauley) writes:
> I have the following code:
> ---cut here
> #include<stdio.h>
> #include<malloc.h>
> main()
> {
>   int *a,*b;
> 
>   ...
>   inita(a,b);
>   printf("main(): a[2]=%d\n",a[2]);
> }
> 	[stuff deleted]

The problem with the code is that "a", is initialized in function inita(), its
value is never known in main().  When you try to print a[2] you get the
SEGV.  Several solutions are possible, you might try either of the
following:

   (1) perform the malloc() for a in main()
   (2) define inita() as a function returning a pointer, e.g.

int *inita (a,b)
int a[],b[];
{
  a=(int *)malloc( (unsigned) 4*sizeof(int));
  a[2]=3;
  printf("inita(): a[2]=%d\n",a[2]);
  printf("inita(): b[2]=%d\n",b[2]);
  return a; 
}

In main() your call would then look like:

   a = inita(a,b);

Hope this helps

-- 
Patrick T. Broderick           |ptb at ittc.wec.com |
                               |uunet!ittc!ptb   |
                               |(412)733-6265    |



More information about the Comp.lang.c mailing list