Click here to Skip to main content
15,896,606 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
#include<stdio.h>
void xstrcpy(char *p, char *q);
main()
{
	char word1[25], word2[25];
	puts("Enter a word");
	gets(word1);
	xstrcpy(word1,word2);
	printf("This is your word1: %s\n and this is word2: %s\n",word1[25],word2[25]);
}
void xstrcpy(char *p, char *q)
{
	q=p;
}


What I have tried:

Basically I am assigning the pointer variable q, the value in p so that the base addresses of the two strings become same. Since strings are stored in contiguous memory locations, the other addresses should change too. But the output is not supportive.
Posted
Updated 11-Mar-16 22:16pm
v2

1 solution

There are three errors.

The first is that a strcpy implementation must copy the data itself. You are not copying the data but assigning one pointer to another. While this is a valid operation, it will not give you the expected results.

The second error is that you perform the assignment using local variables passed as function parameters. These are copies of the pointers to your word strings and will therefore not change them. What you are doing is equivalent to:
C++
char *p = word1;
char *q = word2;
q = p;

If you would print q now, the content of word1 would be printed but the content of the words itself is unchanged.

The third error is in your printf statement where you pass characters instead of strings and have out of bound access. Using word1[25] accesses the character at position 25 in the string. But the printf %s format parameter expects a pointer to charcaters and your strings are only 25 characters wide so that index 25 is invalid (indexes are zero based so that valid ones are from zero to size-1 which is 24 in your case). It should be:
printf("This is your word1: %s\n and this is word2: %s\n",word1,word2);


You should read your course notes or books about C pointers again. Or see for example Pointers - C++ Tutorials[^] (don't be irritated by the C++, the basics described there apply to palin C too).
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900