c - 错误 : assignment of read-only location

标签 c compiler-errors

当我编译这个程序时,我不断得到这个错误

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

我觉得跟指针有关系。我该如何解决这个问题。与常量指针指向常量指针有关系吗?

代码

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

最佳答案

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

在阅读时应用左右规则。

另外请注意,您正在将 r副本 传递给函数 h() -- 如果您想修改 r 那么你必须传递一个非常量指针。

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

关于c - 错误 : assignment of read-only location,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16226313/

相关文章:

compiler-errors - VB6-找不到方法或数据成员

c - C 中的位字段?

c - 无法从共享对象打印到文件

c - 为什么这些构造使用前后递增的未定义行为?

c - 如何更改 pthread_cont_wait 中的互斥体

c# - 缺少类型或命名空间,但正确添加了引用

c++ - C++如何向minGW添加库

c - 文件 I/O 显示 C 中的编译错误

c - 为什么编译器无法检测到我的代码中的减号?

c++ - 重绘整个屏幕的正确方法?