【问题标题】:error: assignment of read-only location错误:分配只读位置
【发布时间】:2013-04-25 23:22:57
【问题描述】:

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

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

【问题讨论】:

  • void h(const Record r) :它已经声明不应该更改r
  • 将参数声明为const 并没有多大作用;它只是阻止函数修改其本地副本。这可能是个好主意,因为它记录并强制您将其保留为传入的原始值,但它对调用者没有影响。
  • 续集见A 'conflicting types' error——不是重复的,而是密切相关的。

标签: c compiler-errors


【解决方案1】:

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

在阅读时应用左右规则。

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

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

【讨论】:

    猜你喜欢
    • 2021-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2012-08-28
    • 1970-01-01
    相关资源
    最近更新 更多