Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   problem in a string copy function (http://www.go4expert.com/forums/string-copy-function-t4082/)

Unitedroad 30Apr2007 17:13

problem in a string copy function
I am a newbie with pointers. I have made this program which has a function that takes one string pointer as the arguement and copies the values stored at the location it points to , to another pointer and then returns that second pointer. This is the source code :

#include <stdio.h>
char *StringCopy(char * NewString1);
main() {
    char String1[80] = "How are you doing?";
    char *StringPointer1, *StringPointer2;
    StringPointer1 = String1;
    StringPointer2 = StringCopy(StringPointer1);
char *StringCopy(char *NewString1) {
    char *NewCopy = NewString1;    //a new character pointer created and initialised to the pointer from formal parameter
    char NewString[80];            //a new character string defined  so as to initialise a new character pointer
    char *NewString2 = NewString;  //a new character pointer initialised to the sting defined in previous line
    char *NewCopy2 = NewString2;  //another pointer defined and made to the location pointed to the pointer defined and initalised in previous line
    while(*NewCopy!='\0') {       
        *NewCopy2++ = *NewCopy++;
    *NewCopy2 = '\0';
    return NewString2;

I think it should work but it giving some gibberish output and I am unable to find out why.\

It works fine when I use puts(NewString2) in StringCopy() fiunction itself.

I am using gcc , I have triend running this program on windows and Mac OS X and I got the problm both times.

I hope someone can help me out

DaWei 30Apr2007 18:29

Re: problem in a string copy function
The pointer you return is valid, but the area to which it points, NewString [80], being local to StringCopy, has been deallocated and (most likely) reused. You need a persistent place to hold the copy. You can get this from the heap, or you can put it in the caller (main) and pass a pointer to it.

I notice that poor Shabbir has had to add code tags to keep your code from being unremittingly ugly and unreadable. Do you think it would be polite to read the "Before you make a query" thread, in return for the free help?

Unitedroad 12May2007 20:49

Re: problem in a string copy function
Hi thanks alot for the help , it has helped me in further grasp the concept of pointers. I am sorry for being careless with my post and I will take car from now on.

All times are GMT +5.5. The time now is 09:19.