How to Return String in C++

Returning string from C function

Either allocate the string on the stack on the caller side and pass it to your function:

void getStr(char *wordd, int length) {
...
}

int main(void) {
char wordd[10 + 1];
getStr(wordd, sizeof(wordd) - 1);
...
}

Or make the string static in getStr:

char *getStr(void) {
static char wordd[10 + 1];
...
return wordd;
}

Or allocate the string on the heap:

char *getStr(int length) {
char *wordd = malloc(length + 1);
...
return wordd;
}

Returning a C string from a function

Your function signature needs to be:

const char * myFunction()
{
return "my String";
}

Background:

It's so fundamental to C & C++, but little more discussion should be in order.

In C (& C++ for that matter), a string is just an array of bytes terminated with a zero byte - hence the term "string-zero" is used to represent this particular flavour of string. There are other kinds of strings, but in C (& C++), this flavour is inherently understood by the language itself. Other languages (Java, Pascal, etc.) use different methodologies to understand "my string".

If you ever use the Windows API (which is in C++), you'll see quite regularly function parameters like: "LPCSTR lpszName". The 'sz' part represents this notion of 'string-zero': an array of bytes with a null (/zero) terminator.

Clarification:

For the sake of this 'intro', I use the word 'bytes' and 'characters' interchangeably, because it's easier to learn this way. Be aware that there are other methods (wide-characters, and multi-byte character systems (mbcs)) that are used to cope with international characters. UTF-8 is an example of an mbcs. For the sake of intro, I quietly 'skip over' all of this.

Memory:

This means that a string like "my string" actually uses 9+1 (=10!) bytes. This is important to know when you finally get around to allocating strings dynamically.

So, without this 'terminating zero', you don't have a string. You have an array of characters (also called a buffer) hanging around in memory.

Longevity of data:

The use of the function this way:

const char * myFunction()
{
return "my String";
}

int main()
{
const char* szSomeString = myFunction(); // Fraught with problems
printf("%s", szSomeString);
}

... will generally land you with random unhandled-exceptions/segment faults and the like, especially 'down the road'.

In short, although my answer is correct - 9 times out of 10 you'll end up with a program that crashes if you use it that way, especially if you think it's 'good practice' to do it that way. In short: It's generally not.

For example, imagine some time in the future, the string now needs to be manipulated in some way. Generally, a coder will 'take the easy path' and (try to) write code like this:

const char * myFunction(const char* name)
{
char szBuffer[255];
snprintf(szBuffer, sizeof(szBuffer), "Hi %s", name);
return szBuffer;
}

That is, your program will crash because the compiler (may/may not) have released the memory used by szBuffer by the time the printf() in main() is called. (Your compiler should also warn you of such problems beforehand.)

There are two ways to return strings that won't barf so readily.

  1. returning buffers (static or dynamically allocated) that live for a while. In C++ use 'helper classes' (for example, std::string) to handle the longevity of data (which requires changing the function's return value), or
  2. pass a buffer to the function that gets filled in with information.

Note that it is impossible to use strings without using pointers in C. As I have shown, they are synonymous. Even in C++ with template classes, there are always buffers (that is, pointers) being used in the background.

So, to better answer the (now modified question). (There are sure to be a variety of 'other answers' that can be provided.)

Safer Answers:

Example 1, using statically allocated strings:

const char* calculateMonth(int month)
{
static char* months[] = {"Jan", "Feb", "Mar" .... };
static char badFood[] = "Unknown";
if (month < 1 || month > 12)
return badFood; // Choose whatever is appropriate for bad input. Crashing is never appropriate however.
else
return months[month-1];
}

int main()
{
printf("%s", calculateMonth(2)); // Prints "Feb"
}

What the static does here (many programmers do not like this type of 'allocation') is that the strings get put into the data segment of the program. That is, it's permanently allocated.

If you move over to C++ you'll use similar strategies:

class Foo
{
char _someData[12];
public:
const char* someFunction() const
{ // The final 'const' is to let the compiler know that nothing is changed in the class when this function is called.
return _someData;
}
}

... but it's probably easier to use helper classes, such as std::string, if you're writing the code for your own use (and not part of a library to be shared with others).

Example 2, using caller-defined buffers:

This is the more 'foolproof' way of passing strings around. The data returned isn't subject to manipulation by the calling party. That is, example 1 can easily be abused by a calling party and expose you to application faults. This way, it's much safer (albeit uses more lines of code):

void calculateMonth(int month, char* pszMonth, int buffersize)
{
const char* months[] = {"Jan", "Feb", "Mar" .... }; // Allocated dynamically during the function call. (Can be inefficient with a bad compiler)
if (!pszMonth || buffersize<1)
return; // Bad input. Let junk deal with junk data.
if (month<1 || month>12)
{
*pszMonth = '\0'; // Return an 'empty' string
// OR: strncpy(pszMonth, "Bad Month", buffersize-1);
}
else
{
strncpy(pszMonth, months[month-1], buffersize-1);
}
pszMonth[buffersize-1] = '\0'; // Ensure a valid terminating zero! Many people forget this!
}

int main()
{
char month[16]; // 16 bytes allocated here on the stack.
calculateMonth(3, month, sizeof(month));
printf("%s", month); // Prints "Mar"
}

There are lots of reasons why the second method is better, particularly if you're writing a library to be used by others (you don't need to lock into a particular allocation/deallocation scheme, third parties can't break your code, and you don't need to link to a specific memory management library), but like all code, it's up to you on what you like best. For that reason, most people opt for example 1 until they've been burnt so many times that they refuse to write it that way anymore ;)

Disclaimer:

I retired several years back and my C is a bit rusty now. This demo code should all compile properly with C (it is OK for any C++ compiler though).

How to return a string in a C function?

str is local to function and will be destroyed once control exits function.

Hence you can try as below.

            char* function (float number)
{
char *str = malloc(30);
strcpy(str, " test");
strcat(str, " char");
return str;
}

int main()
{
char *test = function(5.0);
printf("Hi %s", test);
}

Return a string from function to main

A string is a block of memory of variable length, and C cannot returns such objects (at least not without breaking compatibility with code that assumes strings cannot be returned)

You can return a pointer to a string, and in this case you have two options:

Option 1. Create the string dynamically within the function:

char *funzione (void)
{
char *res = malloc (strlen("Example")+1); /* or enough room to
keep your string */
strcpy (res, "Example");
return res;
}

In this case, the function that receives the resulting string is responsible for deallocate the memory used to build it. Failure to do so will lead to memory leaks in your program.

int main()
{
char *str;

str = funzione();
/* do stuff with str */
free (str);
return 0;
}

Option 2. Create a static string inside your function and returns it.

char *funzione (void)
{
static char str[MAXLENGTHNEEDED];

strcpy (str, "Example");
return str;
}

In this case you don't need to deallocate the string, but be aware that you won't be able to call this function from different threads in your program. This function is not thread-safe.

int main()
{
char *str;

str = funzione();
/* do stuff with str */
return 0;
}

Note that the object returned is a pointer to the string, so on both methods, the variable that receives the result from funzione() is not a char array, but a pointer to a char array.

Return a string from if statement in C

Whoah, there are errors everywhere here!!

If you want to store an array of single chars, just define it as:

char y[5];

Now, the next bit has a few issues:

y[1] == "A";
y[2] == "B";
y[3] == "C";
y[4] == "D";
y[4] == "F";

Apart from the obvious where you're using the comparison operator (==) instead of assignment (=), you were also trying to assign a string literal to a char array. You cannot do this outside of variable's definition. But I assert that you don't want to use strings. You also missed y[0] and doubled-up on y[4].

Since I've already changed your array definition, we need character literals (single-quotes). Let's fix all of this:

y[0] == 'A';
y[1] == 'B';
y[2] == 'C';
y[3] == 'D';
y[4] == 'F';

But that's so much typing... Why not define it in one line, both saving your fingers and making your code more compact (and actually more readable):

char y[5] = { 'A', 'B', 'C', 'D', 'F' };

The next issue is you're returning y[5] for the 'F' score, which is not okay -- that is accessing outside your array: remember indexing is zero-based so the valid indices range from 0 to 4 inclusive. You need to check all your indices, because a few of them are wrong.


My final point is going to be a style-based thing, and you can take it or leave it. Instead of having this big if statement, why not put all your cutoff scores into an array... Rolling this into everything else I've mentioned so far, you'd end up with something like this:

char GradeFromPercentage(float score)
{
const char grades[5] = { 'A', 'B', 'C', 'D', 'F' };
const float scores[5] = { 90.f, 70.f, 50.f, 30.f, -FLT_MAX };
for (int i = 0; i < 5; i++)
{
if (score >= scores[i]) return grades[i];
}

// It should not ordinarily be possible to reach here, but you should
// return something anyway. It's possible to get here if you supply
// a score of `NaN`. You may choose to return an invalid grade, or
// 'F' or whatever.
return '\0';
}

How do you return a formatted string in C?

If you just need to return an allocated string with the full date, your task is quite trivial. You just need to build the string with a function like sprintf:

#include <stdio.h>

char* generateDate(int day, int month, int year)
{
/* here you should place parameters check */

char retString = malloc( 11 );

sprintf (retString, "%02d/%02d/%04d", day, month, year);

return retString;
}

Please note how format %02d prints a 2 digits integer with a leading 0 in case the corresponding integer is only one digit long.

We allocate 11 chars because:

  • 2 are for the day
  • 2 are for the month
  • 4 are for the year
  • 2 are for the separators '/'
  • 1 is required for the string terminator

Of course the function can be improved by inserting parameters check at the beginning of the function, and returning NULL if they are wrong.

  1. Make sure that year is lower than 9999 (for sanity)
  2. Make sure that month is between 1 and 12
  3. With a switch-case conditional, set a variable dayMax to the maximum number of days of every month, and check day so that it is icluded between 1 and dayMax

I can't return a character string in C

Your code doesn't compile because you return char at the calcul() function and returning a character array. If you want to return reseau character array you can do it using pointer. See the difference with the code below with your code to see how to implement it.

You also have some logical problem in your code, like there are no endline in reseau array, which result in printing garbage values after your desire string. and you use one equal = insteed of double equal == to compare equal in your code.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

const char* calcul(char* octet, char* masque);

int main(){
char octetB[]="11000000101010000000000100000111";
char masqueB[]="11111111111111111111111100000000";

printf("octetB : %s\n", octetB);
printf("octetB 3e valeur : %c\n", octetB[2]);

printf("Adresse réseau : %s\n", calcul(octetB, masqueB));
}

const char* calcul(char* octet, char* masque){
int i;
char *reseau = malloc(100);
printf("\n");
printf("octet dans calcul : %s\n", octet);
printf("masque dans calcul : %s\n", masque);

for(i=0; i<32; i++){
if((octet[i]=='1') && (masque[i]=='1')){//use double equal to compare
reseau[i]='1';
} else {
reseau[i]='0';
}
printf("nombre %d : %c\n", i, reseau[i]);
}
reseau[i]= '\0';//add endline
return reseau;
}

How do I return a string in C?

  1. Change int mario(void); to char *mario(void);

  2. Change printf("%c", mario()); to printf("%s", mario());

  3. Move char *result = " "; to the start of the mario() function so it is in-scope for return.



Related Topics



Leave a reply



Submit