pointer->pointer problem

Roy Johnson rjohnson at shell.com
Sat Apr 6 01:47:26 AEST 1991


In article <1991Apr3.174058.13536 at bnlux1.bnl.gov> reilly at bnlux1.bnl.gov (kevin reilly) writes:
>FUNC1 returns the address of an array of pointers to strings.
>FUNC2 does some string manipulations.

>main()
>{
>char **outPt;

>outPut = FUNC1(...);
>FUNC2(outPut);
>}

>char **FUNC1(...)
>{
>static char *lines[10];
>/* do stuff */
>return &lines[0];
>}

>void FUNC2(char **inPut)
>{
>/* If I manipulate the strings pointed to by inPut in this function
	   it seems other strings are also effected.
>   Why is this?
>*/
>}

This sort of problem sure strikes a lot of people.

Nit-pick: You could have FUNC1 return lines, rather than &lines[0]

The real problem is that lines is array of pointers to char, but
you do not (apparently) allocate memory for those pointers to point
to, so you're slogging around in uncharted waters.

Try

char **FUNC1(...)
{
static char lines[10][MAX_STRLEN];
/* do stuff */
return lines;
}

or

in /* do stuff */, you could have

int i;
for (i = 0; i < 10; ++i)
  lines[i]=(char *)malloc(some_length);

where some_length is calculated on the fly.  If you are allocating
space for lines, then I have no answer for why you're getting the
behavior you are.

Hope this helps.
--
======= !{sun,psuvax1,bcm,rice,decwrl,cs.utexas.edu}!shell!rjohnson =======
Feel free to correct me, but don't preface your correction with "BZZT!"
Roy Johnson, Shell Development Company



More information about the Comp.lang.c mailing list