Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

 
 
Thread Tools Display Modes
Prev Previous Post in Thread   Next Post in Thread Next
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
 

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 9:27 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC