Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

370
Visualizações
In C, why can't the value of a pointer-to-char variable be changed after it has been assigned?

I don't understand the difference between this case:

#include <stdio.h>

int main()
{
  int i = 0;
  i = 1;

  return 0;
}

And this case:

#include <stdio.h>

int main()
{
  char *mychar = "H";
  *mychar = "E";

  return 0;
}

Which produces the compiler warning "assignment makes integer from pointer without a cast".

Shouldn't *mychar = "E" dereference mychar to assign it the value of "E"?

Many thanks.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

You have confused few things.

  • Note "E" is actually const char[] which stores 'E' and '\0'. It is not a single character. For single characters you use '', like 'E'.
  • mychar points to string literal and you can't change string literals.

If what you had in mind is this:

 char *mychar = "H";
 mychar = "E"; 

This is ok, you are not changing the string literal, just first time the pointer mychar points to string literal "H", then to "E".

This you can't do:

  char *mychar = "Hello";
  *mychar = 'E'; // Can't modify the string literal

But this you can do:

  char c = 0;
  char *mychar = &c;
  *mychar = 'E'; // This is ok
over 4 years ago · Santiago Trujillo Relatório

0

"E" is a string literal (char*) and 'E' is a char literal (char).

Note that the two pieces of code which you are comparing are not analogous! The difference between the two pieces of code (int vs char*) will be clearer is you write

char* mychar = "H";
*mychar = "E";

The type corresponding to the int example is (char*). That is, the code being analog to the "int" example is

char* mychar = "H";
mychar = "E";
over 4 years ago · Santiago Trujillo Relatório

0

String literals might be stored in read-only section of memory. Modifying a string literal invokes undefined behavior. You can't modify it.

Add const qualifier to let your compiler know that string is non-modifiable

char const *mychar = "H";  

You should also note that the statement

*mychar = "E";  

is wrong by itself. You are assigning a char * type to char.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda