Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Beginner
Oct 20, 1998

User-defined string functions

Question:
I am moving from other languages to Visual C++. I am trying to write a function that returns a string (or pointer to a string), which will then be put into a buffer using the lstrcpy function. I get only the first letter.

Answer:
Please folks, if you ask questions like this, please include a very brief snippet of code. The problem is that pointers and strings work just fine, so you probably have a simple problem with your syntax. Unfortunately, I can only guess at what that might be.

Unless you are using some sort of string class, string pointers are declared as character pointers (char *). To have a function return a pointer to a string, it should be declared as returning char *. If you got that far, then the issue is probably how to assign to that return value. Some beginners might be attempted to do something along the lines of this:

char *GetString()
{
   char s[80];
   strcpy(s, "Here's a sample string!");
   return s;
}
This routine declares a character array, copies a string to it, and then returns a pointer to that array. The problem is that the array is declared local to the function, which means it is deleted as soon as the function returns. So the pointer returned is not safe to use. Instead, the array should be declared as static or outside of the function.
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date