Discuss Program using pointers in the C Programming forum on Dev Shed. Program using pointers C programming forum discussing all C derivatives, including C#, C++, Object-C, and even plain old vanilla C. These languages are low level languages, and used on projects such as device drivers, compilers, and even whole computer operating systems.
Time spent in forums: 1 h 35 m 16 sec
Reputation Power: 0
Program using pointers
I want to simulate the use of strcpy using pointers.
The user enters word "x" and the program copies it into word "y" and prints it on the screen. Here's what I wrote so far I know something's not good in that for . Also please explain what each line does if you provide an answer thank you very much!
printf("Enter word x: ");
for(p=x; *p; p++)
printf("Word y is: %s",y);
Time spent in forums: 3 Months 1 Day 15 h 53 m 15 sec
Reputation Power: 2199
Uh, you wrote it, so you tell us what each line does. Then we can tell you whether you are right.
And do please indent your code!
For a moment, I will assume that you did actually write this (your request screams out to us that you stole^H^H^H^H^Hresearched it from somewhere and are trying to pass it off as your own; it has been tried here far too many times with the exact same request for us to explain what you had allegedly written yourself).
This line, p=y;
does not do what you want it to do. Consider creating two char pointers, one for each string, and use them. Also review how to dereference a pointer.
And please indent your code!
Last edited by dwise1_aol : July 23rd, 2013 at 11:10 AM.
Time spent in forums: 3 Weeks 5 Days 12 h 51 m 9 sec
Reputation Power: 886
Well dwise1_aol gave you the best hint so far. How did you do on your assignment with this one? What does your code look like now?
Basically x and y are just pointers to 100 char buffers on the stack.
Your for loop is bogus. Given x and y you don't actually need p. You can use array indexes. Then your for loop would use int i as an index into both arrays as you increment i until '\0' == x[i]. I would venture a guess that you added p because you couldn't increment y, but then, it's possible this isn't your code. You're not allowed to change the values of x or y because they are arrays.
The way you are using p, it is initially an alias of x ( the 'p=x' statement), but then you make it an alias of y (the 'p=y' statement) and after that the p++ expression makes it an alias for the address of y. All of this pointer manipulation does nothing in the way of copying the string in x to y. But, because your conditional is *p, the loop is likely to run forever because x, y and y probably aren't '\0'.
Now if you put some effort into this, you can still complete your homework assignment.
Good luck and please do let us know how it's going.
I no longer wish to be associated with this site.