C语言 错误:只读位置的分配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16226313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:10:33  来源:igfitidea点击:

error: assignment of read-only location

ccompiler-errors

提问by monkey doodle

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

回答by K Scott Piel

In your function hyou have declared that ris a copy of a constant Record-- therefore, you cannot change ror any part of it -- it's constant.

在您的函数中,h您已声明它r是常量的副本Record——因此,您不能更改r或更改它的任何部分——它是常量。

Apply the right-left rule in reading it.

在阅读时应用左右规则。

Note, too, that you are passing a copyof rto the function h()-- if you want to modify rthen you must pass a non-constant pointer.

也要注意,要传递一个副本r的功能h()-如果要修改r,则必须通过非恒定的指针。

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