How to create a string with a change in the value pointed to by const char *?

I wrote a function that takes a string and returns a const char * that contains an encoded version of that string. I call this function and then create a new line. At the same time, I somehow inadvertently change the value pointing to my const char *, something that I considered impossible.

However, when I do not use my own function, but simply hard-code the value in my const char array, the value does not change when creating the string. Why is there a difference, and why can I change the value of a const char array?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <iostream>

using namespace std;

// returns "@username@FIN"
const char* encodeUsername(string username)
{
    username = "@" + username + "@FIN";
    return username.c_str();
}

int main(void)
{
    string jack("jack");
    const char* encodedUsername = "@jack@FIN";
    string dummy("hi");
    printf("%s\n", encodedUsername); //outputs "@jack@FIN", as expected.

    string tim("tim");
    const char* encodedUsername2 = encodeUsername(tim);
    string dummy2("hi");
    printf("%s\n", encodedUsername2); //outputs "hi". Why?
}
+4
source share
2 answers

, , ++.

  • ++ , . , , . , :
char* moo()
{
    char* a = new char[20];
    strcpy(a, "hello");
    delete[] a;
    return a;
}

, a, . , . , , , , "", delete , .

  1. std::string, , char*, , . std::string , .

  2. - ( encodeUsername username = "@" + username + "@FIN"), , , . , encodeUsername , username , . , , . , c_str(), , .

  3. , , , . , , tim, , encodeUsername.

, ?

-, (, ), :

const char* encodeUsername(string& username)

, username , . , , , , , .

-, char, , :

const char* encodeUsername(string username)
{
    username = "@" + username + "@FIN";
    return strdup(username.c_str());
}

main:

free(encodedUsername);
free(encodedUsername2);

( , free, delete[], strdup)

, char , . , , .

, std::string char, std::string :

string encodeUsername(string username)
{
    username = "@" + username + "@FIN";
    return username;
}

:

string encodedUsername2 = encodeUsername(tim);
printf("%s\n", encodedUsername2.c_str());
+3

username , encodeUsername, , , . , Undefined , , encodeUsername .

, std::string.

+1

Source: https://habr.com/ru/post/1617803/


All Articles