devxlogo

User-defined string functions

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.

See also  Comparing different methods of testing your Infrastructure-as-Code
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist