Q:

Error: Assignment of read-only location in C

belongs to collection: C Common Errors Programs

0

Error: Assignment of read-only location 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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

<< Error: Id returned 1 exit status (undefined refere...