为什么不能将任何整数直接填充到指针变量?

Why not possible to fill any integer straight to a pointer variable?

#include <stdio.h>

int main(void)
{
    int* ptr = NULL;
    *ptr = 10;
    printf("%d", *ptr);
    return 0;
}

我是 C 编程的新手,如果不了解,请提前致歉。 我正在尝试输入一个值,访问分配给 NULL 的指针变量,但它不起作用。

我的猜测是,这是因为 *ptr 应该指向某个数组或变量的地址,如果不指向任何东西,就不能包含值本身。

我的理解正确吗?

是的,你的理解是正确的,你不能做你的代码试图做的事情

int main(void)
{
    int* ptr = NULL;   <<== creates a pointer that points noweher (null)
    *ptr = 10;      <<== store 10 where that pointer points
    printf("%d", *ptr);
    return 0;
}

在第二行中,您尝试在 'ptr' 点处存储 10。但是 'ptr' 没有指向任何地方,结果就是所谓的未定义行为。通常你的程序会在那里停止

你可以这样做

int main(void)
{
    int* ptr = NULL;  <<<=== create pointer to nothing
    int val = 0;       << == create int with value 0
    ptr = &val;       <<<== set ptr to point at val
    *ptr = 10;        <<< ====overwrite val with 10
    printf("%d", *ptr);
    return 0;
}

 *ptr = 10;

和你做的一样

 val = 10;

你也可以

int main(void)
{
    int* ptr = NULL;  <<<=== create pointer to nothing
    ptr = malloc(sizeof(int); <<<== set ptr to point at dynamically allocated int
    if(ptr==NULL) return -1; <<<=== make sure it worked
    *ptr = 10;   <<< === now set that dynamically allocated int to 10
    printf("%d", *ptr);
    return 0;
}

请注意,与前面的示例不同,没有其他方法可以引用 int。 (之前可以互换使用 'val' 和 '*ptr')

My guess is that this is because *ptr is supposed to point some array, or variable's address, cannot contain the value itself without pointing anything.

正确; *ptr = 10; 不会改变 ptr 指向的位置,因此您必须先将其设置为指向可用内存。

int *ptr = NULL;ptr 初始化为 空指针 值,该值本质上意味着“无处可去”。它是一些不等于任何对象或函数地址的值。 (最常见的是,C 实现对空指针使用“零地址”。)

您可以通过多种方式将 ptr 设置为指向可用内存:

int x;
ptr = &x;     // This sets ptr to point to x.

int a[17];
ptr = &a[3];  // This sets ptr to point to a[3].
ptr = &a[0];  // This sets ptr to point to a[0].
ptr = a;      // This also sets ptr to point to a[0].

在最后一个例子中,数组 a 自动转换为指向 a[0] 的指针。

你也可以动态分配内存:

ptr = malloc(sizeof *ptr);
if (ptr == NULL)
{
    fprintf(stderr, "Error, unable to allocate memory.\n");
    exit(EXIT_FAILURE);
}

调用malloc要求系统预留内存。如果成功,则返回内存地址。如果失败,则返回一个空指针,您应该始终通过调用 malloc 后进行测试来处理这种可能性。您可以 #include <stdio.h> 声明 fprintf#include <stdlib> 声明 exitEXIT_FAILURE.

以上任意一项后,可以执行*ptr = 10;将10存入ptr点的地方

当您使用分配的内存时,您通常希望在用完后释放它。您可以通过调用 free(ptr).

来做到这一点

malloc(sizeof *ptr)ptr 指向的类型的一个对象分配足够的内存。您可以使用 ptr = malloc(N * sizeof *ptr)N 个对象分配内存。之后,如果调用成功,可以将值存入ptr[0]ptr[1]、……ptr[N-1].