View Single Post
Old May 23rd, 2006, 3:54 AM   #1
darthsabbath
Newbie
 
Join Date: Dec 2005
Posts: 15
Rep Power: 0 darthsabbath is on a distinguished road
Passing Pointers to Functions

I'm playing around with the classic K&R, and am in the chapter on Pointers. I'm having a bit of a problem with the strcopy() function listed... it keeps segfaulting whenever i compile and run the program. For those who don't have K&R, the code listed is:

/* Copies t to s */
void strcpy(char *s, char *t)
{
        while((*s = *t) != '\0') {
                s++;
                t++;
        }
}

The code I'm using to call the function is
main()
{
	char *p1; /* I've alternately tried pre-setting this to an equal length string to see if that would work... no joy */
	char *p2 = "Now is the time";
	strcpy(p1, p2);
}

The problem seems to be in the while((*s = *t) != '\0') loop. If I don't do the comparison between the two, I can manipulate the passed strings fine... i.e.

while(*t != '\0') {
	printf("%c\n", *t);
	s = t;
	t++;
	s++;
	printf("%c\n", *s);
	
}

I've also tried changing the while loop test to ((s = t) != '\0')... this results in the string being assigned properly... if I pipe out the contents of each char in the strings... I get

N N
o o
w w

i i
s s

t t
h h
e e

t t
i i
m m
e e
^@ ^@
% %
c c

% %
c c

It seems like it's going past the end of the string and into the realm of garbage.

I'm kinda lost, any pointers as to what I'm doing wrong (No pun intended)?

Thanks,
Phil
darthsabbath is offline   Reply With Quote