C++ char* as a function parameter - c++

How can I pass a char pointer (char*) to the function func()?
#include <iostream>
using namespace std;
void func(char *var)
{
cout << var;
}
int main()
{
char* test = "Hello World";
func(test);
}
The compiler says:
Initialization: const char[12] cannot be converted to char *

A string literal is a const char[N] array in read-only memory (where N is the number of characters in the literal, plus 1 for the null terminator, so in your case 11+1=12). You can't point a char* pointer (ie, a pointer to non-const data) at a string literal, as that would allow for the possibility of altering read-only data, which is undefined behavior.
Simply change your pointer type to const char* instead (ie a pointer to const data), eg.
#include <iostream>
using namespace std;
void func(const char *var)
{
cout << var;
}
int main()
{
const char* test = "Hello World";
func(test);
}
Otherwise, as you say you have no control over the function declaration, then if you really want to pass a string literal to a char* pointer, you should copy the characters into a separate writable char[] buffer first, and then point at that instead, eg:
#include <iostream>
using namespace std;
void func(char *var)
{
cout << var;
}
int main()
{
char test[] = "Hello World";
func(test);
}
Or, if you know for sure that the function will never modify the characters, you can just cast off the const-ness using const_cast (though this is highly NOT recommended, I'm including it for completeness), eg:
#include <iostream>
using namespace std;
void func(char *var)
{
cout << var;
}
int main()
{
char* test = const_cast<char*>("Hello World");
func(test);
/* alternatively:
const char* test = "Hello World";
func(const_cast<char*>(test));
*/
}

This code would print the string "Hello World"
void func(char *var)
{
for( ;*var!='\0'; var++) { //!= from null terminator
cout<<*var;
}
}
int main()
{
char test[] = "Hello World";
func(test);
return 0;
}

Related

Assigning const std::string to std::string in c++

I am trying to assign a const std::string variable to std::string variable.But getting some memory related error. code is like below:
#include <iostream>
#include <string>
using namespace std;
std::string sender1;
std::string fun()
{
const std::string sender = "hi";
sender1.assign(sender);
}
int main()
{
fun();
cout<<sender1<<endl;
return 0;
}
You've forgotten a return in fun. If you change that function like this:
std::string fun()
{
const std::string sender = "hi";
sender1.assign(sender);
return sender;
}
then the code will compile and run fine.
I got the answer finally.
We need to declare a char * globally. Then using const_cast <char *> we can convert the constant string to char and assign it.
Example: in .h file:
char * abc;
in .cc file:
func()
{
const std::string cde = "Hello";
//now to use this constant string in another function,we use const cast and
//assign it to abc like below
abc = const_cast <char *>(cde.c_str());
}

how to pass a parameter to char*?

As in the code below, I can't pass this parameter, how do I fix it?
E0167 The "const char *" type argument is incompatible with the "char *" type parameter
Code example:
#include <iostream>
using namespace std;
int PrintString(char* s)
{
cout << s << endl;
}
int main(int argc, char* argv[])
{
PrintString("TESTEEEE");
return 0;
}
I've already tried PrintString(L"TESTEEEE");
I've also tried setting the Project -> Properties -> General -> Character Set option to use Multi-Byte Character Set.
This literal "TESTEEEE" is of type char const[9]. When used as an argument to a function, it can decay to char const* but not to char*. Hence to use your function, you have to make the parameter fit to your argument or the opposite as follows
#include <iostream>
using namespace std;
int PrintString(const char* s)
{
cout << s << endl;
}
int main(int argc, char* argv[])
{
PrintString("TESTEEEE");
return 0;
}
live
OR
#include <iostream>
using namespace std;
int PrintString( char* s)
{
cout << s << endl;
}
int main(int argc, char* argv[])
{
char myArr[] = "TESTEEEE";
PrintString(myArr);
return 0;
}
live
You have incorrect constness, it should be:
void PrintString(const char* s)

C String assigning values in explicit constructor in C++?

I have a class BankAccount with two string members - name and num. What I want is to assign values to these objects when I create them (when the constructor is called). However the compiler says No instance of constructor matches the argument list when I try to create an object.
I would like to ask why is that?
// hwk-2.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "pch.h"
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
class BankAccout {
char name[23];
char num[15];
double sum;
public:
BankAccout(char *nm, char *nr, double s) {
strcpy(name,nm);
strcpy(num, nr);
sum = s;
}
};
int main()
{
BankAccout k("Peter", "0403940940", 34.21);
}
as a coffee break exercise here is more idiomatic version
#include "pch.h"
#include <iostream>
#include <string>
class BankAccount {
std::string name_;
std::string num_;
double sum_;
public:
BankAccount(std::string name, std::string num, double sum) {
name_ = name;
num_ = num;
sum_ = sum;
}
};
int main()
{
BankAccount k("Peter", "0403940940", 34.21);
}
The signature of the constructor does not match.
This one will match:
BankAccount(const char *nm, const char *nr, double s);
EDIT:
The reason is the way you are calling the constructor in the main function. You are giving literal strings as parameters. These literals are const, you cannot change them at runtime. Thus you will pass pointers to const char*.
This is very obvious if you look at this opposing example. This is a way that would be compatible with the old signature BankAccout(char *nm, char *nr, double s);.
int main(int argc, char* argv[])
{
char name[] = "hello";
char number[] = "1234";
std::cout << "name before: " << name << std::endl;
BankAccount k(name, number, 8.5);
// name and number are not const,
// you can change them :
name[2] = 'x';
name[3] = 'x';
std::cout << "name after: " << name << std::endl;
return 0;
}
An even simpler version, if you don’t need to have additional functionality in the class: just use a struct.
#include <string>
struct BankAccount {
std::string name;
std::string number;
double balance;
};
int main() {
BankAccount account{"Joy", "44", 43.};
}

How to pass a string as default argument in C++

How can I properly pass a const string, for example: "Hello" as a default parameter to a constructor without getting any warnings and errors? In other words how can I preserve memory for them before the function is called?
#include <iostream>
const char *defString = "Hello";
void foo(const char *str = defString) {
std::cout << str;
}
int main() {
foo();
foo("Hello, world!\n");
}

Returning a C string stored in a class

I am trying to print out a C string that is stored in a class by returning the value using an accessor function.
Thanks for any help!
This is the error I get when I compile:
cstringClass.cpp: In member function 'char Foo::get_name()':
cstringClass.cpp:37:9: error: invalid conversion from 'char*' to 'char' [-fpermi
ssive]
return name;
^
Here is the code:
#include <iostream>
#include <cstring>
using namespace std;
class Foo
{
public:
void set_name(char a[]);
char get_name();
private:
char name[10];
};
int main()
{
Foo bar;
char a[10] = "Test";
bar.set_name(a);
cout << bar.get_name();
return 0;
}
void Foo::set_name(char a[])
{
strcpy(name, a);
}
char Foo::get_name()
{
return name;
}
So the error says:
cstringClass.cpp: In member function 'char Foo::get_name()':
^^^^^^^^^^^^^^^^^^^^
And indeed:
char get_name();
You declared get_name as returning a single char, not a pointer to a string. You probably meant char *get_name();.
As the error message states, your get_name() function doesn't return the appropriate type, which should be char* based on the data it returns, which is name[10]. char returns only 1 byte of data and name[10] has 10. Please see the corrected code below.
#include <iostream>
#include <cstring>
using namespace std;
class Foo
{
public:
void set_name(char a[]);
char *get_name(); //<-- correction
private:
char name[10];
};
int main()
{
Foo bar;
char a[10] = "Test";
bar.set_name(a);
cout << bar.get_name();
return 0;
}
void Foo::set_name(char a[])
{
strcpy(name, a);
}
char *Foo::get_name() //<-- correction
{
return name;
}