错误:分配只读位置

mon*_*dle 3 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
Run Code Online (Sandbox Code Playgroud)

我认为它与指针有关.我该如何解决这个问题.它是否与指向常量指针的常量指针有关?

码

#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';
}
Run Code Online (Sandbox Code Playgroud)

K S*_*iel 5

在你的函数中,h你已声明它r是一个常量的副本Record- 因此,你不能改变r它的任何部分 - 它是常数.

在阅读时应用左右规则.

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

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