custom string to char converstion function not working?

I wrote this custom programme to convert a string to char but its giving garbage value
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  // string to char
#include <iostream>
#include <cstring>

char stc(std::string str){
char ch[1024];
strncpy(ch, str.c_str(), sizeof(ch));
ch[sizeof(ch) - 1] = 0;

}
int main()
{
  
  std::string exp="Hello World";
  std::cout<<stc(exp);
  return 0;


}
You forgot to add a return statement to the function.

I'm not sure exactly what you want to return from that function. If your plan is to return a pointer to the ch array that will not work because a char can only store a single character. If you change the return type to char* it would still not work because ch is a local variable inside the function and as soon as the function ends it would no longer exist.

If all you want is to get a char* from a std::string why not simply use the c_str() function right away? That's what it's for.
Last edited on
Thanks I didnt know about such function already existed. Thank you
Last edited on
closed account (48T7M4Gy)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <string>

char* str_to_cstr( const std::string );

int main()
{
    std::string str = "Hello World!";
    
    char* cstr = str_to_cstr(str);
    std::cout << cstr << '\n';
    delete[] cstr;
    
    return 0;
}

char* str_to_cstr(const std::string aString)
{
    size_t size = aString.length() + 1;
    char* aCstr = new char[size];
    
    for( size_t i = 0; i < size; i++ )
        aCstr[i] = aString[i];
    aCstr[size] = '\0';
    
    return aCstr;
}
I didnt know about such function already existed.

You did actually use it in the stc function (line 7).
@kemort thank you for the code @peter87 I am in my learning stage and i copied the above code from another site
Last edited on
closed account (48T7M4Gy)
I wrote this custom programme
and
i copied the above code from another site


It's not as though any of us are going to call the police but I can't help highlighting the questionable mutual exclusivity of those two statements.

Perhaps we just need to laugh along together while taking note of the replies that do make sense :)
Topic archived. No new replies allowed.