2
當我編譯這個程序,我不斷收到此錯誤錯誤:只讀位置的分配
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'。 – BLUEPIXY 2013-04-25 23:28:44
將參數聲明爲'const'並沒有太大的作用;它只是防止該功能修改其本地副本。這可能是一個好主意,因爲它會記錄並強制您將其保留爲傳入的原始值,但對調用方沒有影響。 – 2013-04-25 23:37:30
查看[續集'衝突類型'錯誤](http://stackoverflow.com/questions/16226540/have-a-conflicting-types-error) - 不是重複的,但密切相關。 – 2013-04-25 23:54:57