错误:只读位置分配 [英] error: assignment of read-only location

查看:679
本文介绍了错误:只读位置分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  example4.c:在函数'H':
example4.c:36:错误:只读位置分配
example4.c:37:错误:只读位置分配

我认为这是与指针。我如何去修复这一点。它有恒定的指针做被指向到恒指针?

code

 的#include<&stdio.h中GT;
#包括LT&;&string.h中GT;
#包括example4.h诠释的main()
{
        记录值,* PTR;        PTR =安培;价值;        value.x = 1;
        的strcpy(value.s,XYZ);        F(PTR);
        的printf(X%的D \\ n值,PTR - > X);
        的printf(S的%s \\ n值,ptr-> S);
        返回0;
}无效F(记录* R)
{
R-&X的催化剂* = 10;
        (* R).S [0] ='A';
}无效克(记录r)
{
        r.x * = 100;
        R,S [0] ='B';
}无效小时(const的记录r)
{
        r.x * = 1000;
        R,S [0] =C;
}


解决方案

在你的函数 ^ h 您已经声明研究是一个常数录制的副本 - 因此,你不能改变研究或任何部分 - 这是不变的。

适用于阅读它的右 - 左的规则。

请注意,那就是,要传递一个复制 研究到功能 H() - 如果你想修改研究,那么你必须通过一个非恒定的指针

 无效小时(录音* R)
{
        R-&X的催化剂* = 1000;
        R-> S [0] =C;
}

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

解决方案

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.

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.

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

这篇关于错误:只读位置分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆