×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

Error: Assignment of read-only location in C

Here, we are going to learn why an Error: Assignment of read-only location in C occurs and how to fixed in C programming language?
By IncludeHelp Last updated : March 10, 2024

Error: Assignment of read-only variable in C

Error: assignment of read-only location occurs when we try to update/modify the value of a constant, because the value of a constant cannot be changed during the program execution, so we should take care about the constants. They are read-only.

Consider this example:

Example

#include <stdio.h>

int main(void){
	//constant string (character pointer)
	const char *str = "Hello world";
	
	//changing first character
	str[0] ='p';  //will return error	
	printf("str: %s\n",str);
	
	return 0;
}

Output

main.c: In function 'main':
main.c:8:9: error: assignment of read-only location '*str'
  str[0] ='p';  //will return error 
         ^

Here, the statement str[0]='p' will try to change the first character of the string, thus, the "Error: assignment of read-only location" will occur.

How to fix?

Do not change the value of a constant during program execution.

C Common Errors Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.