Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: assignment of read-only location

When I compile this program, I keep getting this error

example4.c: In function ‘h’:
example4.c:36: error: assignment of read-only location
example4.c:37: error: assignment of read-only location

I think it has something to do with the pointer. how do i go about fixing this. does it have to do with constant pointers being pointed to constant pointers?

code

#include <stdio.h>
#include <string.h>
#include "example4.h"

int main()
{
        Record value , *ptr;

        ptr = &value;

        value.x = 1;
        strcpy(value.s, "XYZ");

        f(ptr);
        printf("\nValue of x %d", ptr -> x);
        printf("\nValue of s %s", ptr->s);


        return 0;
}

void f(Record *r)
{
r->x *= 10;
        (*r).s[0] = 'A';
}

void g(Record r)
{
        r.x *= 100;
        r.s[0] = 'B';
}

void h(const Record r)
{
        r.x *= 1000;
        r.s[0] = 'C';
}
like image 358
monkey doodle Avatar asked Apr 25 '13 23:04

monkey doodle


People also ask

What is read-only location?

Read-only is a file attribute, or a characteristic that the operating system assigns to a file. In this case, read-only means that the file can be only opened or read; you cannot delete, change, or rename any file that's been flagged read-only.

What does assignment of read-only variable mean?

Error “assignment of read-only variable in C” occurs, when we try to assign a value to the read-only variable i.e. constant.


1 Answers

In your function h you have declared that r is a copy of a constant Record -- therefore, you cannot change r or any part of it -- it's constant.

Apply the right-left rule in reading it.

Note, too, that you are passing a copy of r to the function h() -- if you want to modify r then you must pass a non-constant pointer.

void h( Record* r)
{
        r->x *= 1000;
        r->s[0] = 'C';
}
like image 130
K Scott Piel Avatar answered Oct 25 '22 01:10

K Scott Piel