Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

374
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!