Home
Aptitude
Categories


Home » C programs » Common C program Errors

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?
Submitted by IncludeHelp, on December 06, 2018

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:

#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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.