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.
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With