gpt4 book ai didi

c - 为什么将取消引用指针设置为等于原语是非法的?

转载 作者:行者123 更新时间:2023-11-30 18:22:28 25 4
gpt4 key购买 nike

为什么设置取消引用的指针的值会引发段错误 11?为了让我的意思更清楚,请看下面的代码:

#include <stdio.h>

int *ptr;
*ptr = 2;

int main(){
printf("%d\n", *ptr);
return 0;
}

我以为 *ptr=2 会将指针 ptr 指向的右值设置为 2。事实不是这样吗?如果对于那些 C 专家程序员来说,这真的很简单/显而易见,我深表歉意。

是否只允许将取消引用的指针(即 *ptr)设置为某个值(如果该值具有内存地址)?即喜欢做:

int k = 7;
int *ptr = k;

然后:

*ptr = 2;

最佳答案

这里的问题是 ptr 没有指向分配的空间。请参阅以下内容:

#include <stdio.h>
#include <stdlib.h>

int main(void){

// Create a pointer to an integer.
// This pointer will point to some random (likely unallocated) memory address.
// Trying set the value at this memory address will almost certainly cause a segfault.
int *ptr;

// Create a new integer on the heap, and assign its address to ptr.
// Don't forget to call free() on it later!
ptr = malloc(sizeof(*ptr));

// Alternatively, we could create a new integer on the stack, and have
// ptr point to this.
int value;
ptr = &value;

// Set the value of our new integer to 2.
*ptr = 2;

// Print out the value at our now properly set integer.
printf("%d\n", *ptr);

return 0;
}

关于c - 为什么将取消引用指针设置为等于原语是非法的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21151653/

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