Muhammad Sohail
Muhammad Sohail

Reputation: 19

Change char variable values and print using pointers

I want to change char fruitvariable 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

Answers (5)

Jarod42
Jarod42

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

Anson Tan
Anson Tan

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;
}

enter image description here

Upvotes: 1

Nishant
Nishant

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

Ali Kazmi
Ali Kazmi

Reputation: 1458

change it like this char *fruit="Apple"; char *ptr_fruit=fruit;

it should work

Upvotes: -1

Leśny Rumcajs
Leśny Rumcajs

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:

  1. Declare large enough buffer for your fruits char fruit[50] = "Apple"
  2. Use strncpy for copying and some temp containers.

Upvotes: 3

Related Questions