How do I return a char array from a function?
Best as an out parameter:
void testfunc(char* outStr){
char str[10];
for(int i=0; i < 10; ++i){
outStr[i] = str[i];
}
}
Called with
int main(){
char myStr[10];
testfunc(myStr);
// myStr is now filled
}
How can I return a character array from a function in C?
You've got several options:
1) Allocate your array on the heap using malloc()
, and return a pointer to it. You'll also need to keep track of the length yourself:
void give_me_some_chars(char **arr, size_t *arr_len)
{
/* This function knows the array will be of length 2 */
char *result = malloc(2);
if (result) {
result[0] = 'c';
result[1] = 'a';
}
/* Set output parameters */
*arr = result;
*arr_len = 2;
}
void test(void)
{
char *ar;
size_t ar_len;
int i;
give_me_some_chars(&ar, &ar_len);
if (ar) {
printf("Array:\n");
for (i=0; i<ar_len; i++) {
printf(" [%d] = %c\n", i, ar[i]);
}
free(ar);
}
}
2) Allocate space for the array on the stack of the caller, and let the called function populate it:
#define ARRAY_LEN(x) (sizeof(x) / sizeof(x[0]))
/* Returns the number of items populated, or -1 if not enough space */
int give_me_some_chars(char *arr, int arr_len)
{
if (arr_len < 2)
return -1;
arr[0] = 'c';
arr[1] = 'a';
return 2;
}
void test(void)
{
char ar[2];
int num_items;
num_items = give_me_some_chars(ar, ARRAY_LEN(ar));
printf("Array:\n");
for (i=0; i<num_items; i++) {
printf(" [%d] = %c\n", i, ar[i]);
}
}
DO NOT TRY TO DO THIS
char* bad_bad_bad_bad(void)
{
char result[2]; /* This is allocated on the stack of this function
and is no longer valid after this function returns */
result[0] = 'c';
result[1] = 'a';
return result; /* BAD! */
}
void test(void)
{
char *arr = bad_bad_bad_bad();
/* arr is an invalid pointer! */
}
How to return a char array created in function?
The simplest way would be to return a std::string
, and if you needed access to the internal char array use std::string::c_str()
.
#include <iostream>
#include <string>
using namespace std;
string myGoodFunction(){
char charArray[] = "Some string\n";
return string(charArray);
}
int main(int argc, char** argv) {
cout << myGoodFunction();
return 0;
}
If you need to return something other than a char array, remember that pointers can be used as iterators. This allows you to encapsulate an array in a vector or a similar structure:
vector<int> returnInts() {
int someNums[] = { 1, 2, 3, 4 };
return vector<int>(someNums, someNums + 4);
}
Return char[]/string from a function
Notice you're not dynamically allocating the variable, which pretty much means the data inside str
, in your function, will be lost by the end of the function.
You should have:
char * createStr() {
char char1= 'm';
char char2= 'y';
char *str = malloc(3);
str[0] = char1;
str[1] = char2;
str[2] = '\0';
return str;
}
Then, when you call the function, the type of the variable that will receive the data must match that of the function return. So, you should have:
char *returned_str = createStr();
It worths mentioning that the returned value must be freed to prevent memory leaks.
char *returned_str = createStr();
//doSomething
...
free(returned_str);
How can I return an char array from a function using malloc
Your array is local, we need to declare it dynamically. Please try below sample code.
char **arr = NULL;
arr = (char**)malloc(words*sizeof(char*))
/* then use it */
return arr;
How to return private char array from member function?
private or public is not matter. your problem is return char
instead of char*
.
I suggest you to use string instead of char array.
#include <iostream>
using namespace std;
class TEST
{
char n[10];
public:
char* getname()
{
cout<<"what's your name?:";
cin.getline(n,10);
return n;
}
};
int main()
{
char* name;
TEST obj;
name = obj.getname();
cout<<"Name :"<<name;
}
Returning char array in C function
char *resultPtr = &result;
return resultPtr;
You can't do this. result
doesn't exist when function ends, you can't return result
.
Modify your function like this:
void encryptDecrypt(char *text, char *result)
{
for (int i = 0; i < LENGTH - 1; i++)
{
result[i] = (char)(text[i] ^ KEY[i]);
}
}
create an array at the caller site, and pass it as result
. e.g.
char result[LENGTH] = {0};
encryptDecrypt(plainText, result);
NOTE: Actually using %s
for printing encrypted data is not best idea, because for example as a result of XOR you may get a null byte in between the text, which will be considered as a null terminator for your string, and printf
won't show rest of the string. Consider something like this for printing cipher text.
Your format specifier for strlen
is also wrong, use %zu
insted of %i
, or you will trigger undefined behaviour.
Related Topics
Default, Value and Zero Initialization Mess
C++ Templates Specialization Syntax
Allow for Range-Based for with Enum Classes
Using Boost to Read and Write Xml Files
Is It a Good Practice to Define C++ Functions Inside Header Files
When Should I Use Typedef in C++
C++ - Passing References to Std::Shared_Ptr or Boost::Shared_Ptr
How to Use Doxygen to Create Uml Class Diagrams from C++ Source
Most Optimized Way of Concatenation in Strings
How to Programmatically Cause a Core Dump in C/C++
How to Use a Third-Party Dll File in Visual Studio C++
Iterative Dfs VS Recursive Dfs and Different Elements Order
How to Draw Text Using Only Opengl Methods
Why Do Some People Use Swap for Move Assignments