Home > Net >  How change the second letter in char *name = "exemple"; with char *name
How change the second letter in char *name = "exemple"; with char *name

Time:06-19

I am studying c to get a good understanding of memory.

char *name = "example"; 

*(&name 1) = (char*)'A';

std::cout << name << std::endl;

is returning example not eAample.

My idea is to get the memory address of 'x' and changed it.

Is not a const so I should be able to change the value of the address right?

obs: I know how do it in other ways, I am curious to make this way.

CodePudding user response:

This declaration

char *name = "example";

is invalid.

In C string literals have types of constant character arrays. It means that you have to write

const char *name = "example";

and you may not change the string literal.

Even in C where string literals have types of non-constant character arrays you may not change a string literal. Any attempt to change a string literal results in undefined behavior.

This expression

&name 1

points outside the pointer name. So dereferencing the pointer expression *(&name 1) invokes undefined behavior.

Also this expression (char*)'A' does not make a sense. It denotes that you are trying to use the value of the code of the character 'A' (that for example in ASCII is equal to 65) as an address of memory.

What you could do is the following

char name[] = "example"; 

*(name 1) = 'A';

std::cout << name << std::endl;

Or if you want to deal with pointer expressions then instead of

*(name 1) = 'A';

you could write

*(name 1) = *"A";

Here is a demonstration program that is based on your idea. The first range-based for loop will be compiled by a compiler that supports C 20. Otherwise you can rewrite it like

const char **p = name; 
for ( const auto &letter : "example")

Here you are.

#include <iostream>

int main()
{
    const char *name[sizeof( "example" )]; 

    for ( const char **p = name; const auto &letter : "example")
    {
        *p   = &letter;
    }

    *( name   1 ) = &"A"[0];

    for ( const char **p = name; **p;   p )
    {
        std::cout << **p;
    }
    std::cout << '\n';
} 

The program output is

eAample
  • Related