gpt4 book ai didi

c - 指针及其取消引用的方法

转载 作者:行者123 更新时间:2023-11-30 18:32:14 24 4
gpt4 key购买 nike

我对取消引用指针有疑问我编写了一个简单的代码,但我不知道它在某些情况下失败的原因,有人可以告诉它失败的原因是什么。如果我们有 char *ptr = "stack overflow"那么编译器自己会为其分配内存。

int main()
{
int *ptr = 10;
double *dptr = 111.111
printf("%d", *ptr); //will give segmentation violation as we are trying to access the content in location 10
printf("%d", ptr);//o/p will be 10
printf("%lf", dptr); // will give segmentation violation
printf("%lf", *dptr); // will give segmentation violation

}

最佳答案

int *ptr = 10;
double *dptr = 111.111

问题出在上面两行。

ptr指向地址10,而dptr我不知道它指向哪里。

取消引用这些指针肯定会产生未定义的行为..通常是分段违规错误。

修复:

int main(){
int iVal = 10;
double dVal = 111.11;

int *ptr = &iVal;
double *dptr = &dval;

printf("%d", *ptr); // ok
printf("%p", (void *)ptr);// ok
printf("%p", (void *)dptr); // ok
printf("%lf", *dptr); // ok
return 0;
}
<小时/>

理论:指针是一个保存地址的变量 - 或者正如 Alexey Frunze 所说:

The C standard does not define what a pointer is internally and how it works internally. This is intentional so as not to limit the number of platforms, where C can be implemented as a compiled or interpreted language.

A pointer value can be some kind of ID or handle or a combination of several IDs (say hello to x86 segments and offsets) and not necessarily a real memory address. This ID could be anything, even a fixed-size text string. Non-address representations may be especially useful for a C interpreter.

关于c - 指针及其取消引用的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15517411/

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