Returning strings from functions

Returning strings from functions

Question:
I would like to write a function that receivesan integer and converts this into a string representing the integers value in binary. At the moment I am struggling to get the function to return a string. Do I have to get the function to return a pointer to the string? If so how is this declared and called?

Answer:
If you are using C++, you would probably want to return a pointer to some sort of String object. Assuming you are just using C then, yes, you would want to return a pointer to that string.

The only tricky part is due to the fact that variables declared within your function are destroyed when your function returns. Some ways of handling this include allocating memory from the system, which requires that the caller free that memory when it is done, or allocate the string data outside of your function so it is not destroyed when the function returns.

Perhaps the simplest approach is to simply declare a local string as static so that it is not destroyed.

char *GetString(){   static char s[80];   strcpy(s, “Here is a string!”);   return s;}

Share the Post:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several