Question about pointer

Art Neilson art at pilikia.pegasus.com
Sun Mar 3 05:52:32 AEST 1991


In article <2488 at njitgw.njit.edu> yxz1684 at hertz.njit.edu (Ying Zhu ee) writes:
>The following is a small program from "Mastering C pointers" by Robert J.
>Traister. I am confusing with the pointer here. Since the r[100] is an
>automatic variable, after calling the "combine" the r[100] will be deallocated.
>Then the p will point to an unsafe place. Actually, runing this program
>on VAXII/GPX(ULTRIX) and Sparc( BSD UNIX ) here have different answers. Any
>one familiar with C  can help me? Thank you!

You are right, it is unsafe as storage for automatic r within
function combine is released upon return to main.

>main()
>{
>    char a[10], b[10], *p, *combine();
>
>    strcpy( a, "horse" );
>    strcpy( b, "fly" );
>
>    p=combine(a, b);

Why not use strcat(3) instead of the combine() function ?
(of course you'd have to declare a[20])

     p=strcat(a, b);

I guess it'd defeat the purpose of the excersize.

>    printf("%s\n", p );
>}
>
>char *combine(s,t)
>char *s, *t;
>{
>     int x,y;
>     char r[100];
>
>     strcpy(r,s);
>     y=strlen(r);
>     for ( x=y; *t != '\0'; ++x )
>         r[x] = *t++;
>     r[x]='\0';
>
>     return(r);
>}
-- 
Arthur W. Neilson III		| INET: art at pilikia.pegasus.com
Bank of Hawaii Tech Support	| UUCP: uunet!ucsd!nosc!pilikia!art



More information about the Comp.lang.c mailing list