错误:分配只读位置

时间:2021-06-16 09:48:29

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';
}

1 个解决方案

#1


5  

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.

在函数h中,你已经声明r是一个常数记录的拷贝——因此,你不能改变r或者它的任何一部分——它是常数。

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.

还请注意,您正在向函数h()传递一个r的副本——如果您想修改r,那么您必须传递一个非常量指针。

void h( Record* r)
{
        r->x *= 1000;
        r->s[0] = 'C';
}

#1


5  

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.

在函数h中,你已经声明r是一个常数记录的拷贝——因此,你不能改变r或者它的任何一部分——它是常数。

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.

还请注意,您正在向函数h()传递一个r的副本——如果您想修改r,那么您必须传递一个非常量指针。

void h( Record* r)
{
        r->x *= 1000;
        r->s[0] = 'C';
}