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 : Code: #include <stdio.h> char *StringCopy(char * NewString1); main() { char String1[80] = "How are you doing?"; char *StringPointer1, *StringPointer2; StringPointer1 = String1; StringPointer2 = StringCopy(StringPointer1); puts(StringPointer2); } 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
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?
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.