gpt4 book ai didi

c - const int 指针的行为 - C

转载 作者:太空宇宙 更新时间:2023-11-04 05:26:50 26 4
gpt4 key购买 nike

我有一个C程序

#include<stdio.h>

void f(const int* p)
{
int j;
p = &j;
j = 10;
printf("Inside function *p = %d\n",*p);
*p = 5;
printf("Inside function *p = %d\n",*p);
j = 7;
printf("Inside function *p = %d\n",*p);
}

int main()
{
int i = 20, *q = &i;
f(q);
}

程序编译报错

Assignment of the read only location *p

在行 *p = 5;

为什么赋值 j = 10; 是有效的而 *p = 5; 是错误的。

最佳答案

const int *p 表示您不能修改 p 指向使用 p 的整数,如 *p = 5;。它指向的整数可能不是 const int,这就是 j = 10 起作用的原因。这可以防止编码人员修改指向的整数。

关于c - const int 指针的行为 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22241125/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com