Reputation: 19
I want to change char fruit
variable value from Apple
to Orange
using pointer technique please can anybody help me to solve my problem.
Here is the the code.
#include <iostream>
using namespace std;
int main()
{
char fruit='Apple';
char *ptr_fruit;
ptr_fruit=&fruit;
*ptr_fruit='Orange';
cout<< fruit;
system("PAUSE");
}
Upvotes: 0
Views: 133
Reputation: 217573
You probably want:
const char* fruit = "Apple";
const char** ptr_fruit = &fruit;
*ptr_fruit = "Orange"; // now fruit is "Orange"
but I think following is easier to understand by the introduction of a typedef
to avoid the **
which may be confusing.
using c_string = const char*; // or `typedef const char* c_string;`
c_string fruit = "Apple";
c_string* ptr_fruit = &fruit;
*ptr_fruit = "Orange"; // now fruit is "Orange"
The two code snippet are equivalent.
Upvotes: 0
Reputation: 1246
Is this something you want ?
#include <iostream>
int main()
{
char const *fruit="Apple";
char const **ptr_fruit;
ptr_fruit = &fruit;
*ptr_fruit = "Orange";
std::cout << fruit;
}
Upvotes: 1
Reputation: 1665
1: You declare an array like this
char Fruit[] = "Apple";
See the brackets and double quotes?
What you are doing is to declare a char variable, because when you put something in ""
(double quotes), it is considered as a string, when you put it in ''
(Single quotes), it is considered as character by the compile.
2: When you say *ptr_fruit
,compiler treats it as ptr_fruit[0]
. So you will get error in that line too.
Upvotes: 0
Reputation: 1458
change it like this char *fruit="Apple"; char *ptr_fruit=fruit;
it should work
Upvotes: -1
Reputation: 2516
You should review the basics of C++. And abandon char* for std::string. Anyway, some tips if you really want to use this approach:
char fruit[50] = "Apple"
Upvotes: 3