Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the contents of a pointer variable

Tags:

c++

pointers

In this code:

#include <iostream>
int main()
{
const char* name = "Abc";
std::cout<<*name<<std::endl;
return 0;
}

How can I change the contents of the pointer variable, not to what it is pointing at?

And, why am I just getting A as output from this program?

Thanks.

like image 319
Simplicity Avatar asked Jan 28 '11 11:01

Simplicity


People also ask

How do I change the value of a pointer variable?

Steps: Declare a pointer of same type. Initialize the pointer with the other (normal variable whose value we have to modify) variable's address. Update the value.

Can we change the value of a pointer?

We can change the pointer's value in a code, but the downside is that the changes made also cause a change in the original variable.

Can a pointer variable be changed within a function?

When you use pass-by-pointer, a copy of the pointer is passed to the function. If you modify the pointer inside the called function, you only modify the copy of the pointer, but the original pointer remains unmodified and still points to the original variable.

How do I change the value of a pointer in CPP?

You can change the address value stored in a pointer. To retrieve the value pointed to by a pointer, you need to use the indirection operator * , which is known as explicit dereferencing. Reference can be treated as a const pointer. It has to be initialized during declaration, and its content cannot be changed.

Can you change the value of a variable in C?

Master C and Embedded C Programming- Learn as you go In C or C++, we can use the constant variables. The constant variable values cannot be changed after its initialization.


1 Answers

You get a char because you are de-referencing a char* pointer.

You could change the contents by doing:

*a = 'B'; // your char* would contain "Bbc"
a[0] = 'B'; // your char* would contain "Bbc"
a[1] = 'B'; // your char* would contain "ABc"
a[2] = 'B'; // your char* would contain "AbB"

But, changing the contents of a string literal has an undefined behavior in C. So you should not do that. Instead, you need to populate your char* dynamically. With something like this:

char *a;
a = malloc(sizeof(char)*100); // a string with a maximum of 99 chars
strcpy(a, "Abc");
// now you can safely change char* contents:
a[0] = '1';
a[1] = '1';
a[2] = '1';
printf("%s", a); // will print 111

String manipulation is not that easy in languages like C. Since by the syntax you are using, you seem to be compiling your code with a C++ compiler, then you might give string class a try instead of using pointers to char to handle your strings.

like image 192
Pablo Santa Cruz Avatar answered Sep 20 '22 15:09

Pablo Santa Cruz