直接赋值给C指针。

时间:2022-09-25 08:58:14

I've just started learning C and I've been running some simple programs using MinGW for Windows to understand how pointers work. I tried the following:

我刚刚开始学习C语言,我一直在运行一些简单的程序,使用MinGW来了解指针是如何工作的。我试着以下:

#include <stdio.h>

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

which compiled properly but when I run the executable it doesn't work - the value isn't printed to the command line, instead I get an error message that says the .exe file has stopped working.

编译正确,但当我运行可执行文件时,它不起作用——这个值并没有被打印到命令行,相反,我得到一个错误消息,说.exe文件已经停止工作。

However when I tried storing the value in an int variable and assign *ptr to the memory address of that variable as shown below:

但是,当我尝试将值存储在一个int变量中,并将*ptr分配到该变量的内存地址时,如下所示:

#include <stdio.h>

int main(){
    int *ptr;
    int q = 50;
    ptr = &q;
    printf("%d", *ptr);
    return 0;
}

it works fine.

它将正常工作。

My question is, why am I unable to directly set a literal value to the pointer? I've looked at tutorials online for pointers and most of them do it the same way as the second example.

我的问题是,为什么我不能直接将文本值设置为指针?我在网上看了一些指导教程,其中大多数都和第二个例子一样。

Any help is appreciated.

任何帮助都是感激。

3 个解决方案

#1


26  

The problem is that you're not initializing the pointer. You've created a pointer to "anywhere you want"—which could be the address of some other variable, or the middle of your code, or some memory that isn't mapped at all.

问题是您没有初始化指针。您已经创建了一个指向“您想要的任何地方”的指针——它可能是某个其他变量的地址,或者是代码的中间部分,或者是一些根本没有映射的内存。

You need to create an int variable somewhere in memory for the int * variable to point at.

您需要在内存中为int *变量创建一个int变量。

Your second example does this, but it does other things that aren't relevant here. Here's the simplest thing you need to do:

第二个例子是这样的,但它做的其他事情与这里无关。下面是你需要做的最简单的事情:

int main(){
    int variable;
    int *ptr = &variable;
    *ptr = 20;
    printf("%d", *ptr);
    return 0;
}

Here, the int variable isn't initialized—but that's fine, because you're just going to replace whatever value was there with 20. The key is that the pointer is initialized to point to the variable. In fact, you could just allocate some raw memory to point to, if you want:

这里,int变量不是初始化的,但这很好,因为你只需要用20来替换所有的值。关键是指针被初始化以指向变量。事实上,你可以分配一些原始内存来指向,如果你想:

int main(){
    void *memory = malloc(sizeof(int));
    int *ptr = (int *)memory;
    *ptr = 20;
    printf("%d", *ptr);
    free(memory);
    return 0;
}

#2


7  

First Program with comments

第一个程序与评论

#include <stdio.h>

int main(){
    int *ptr;             //Create a pointer that points to random memory address

    *ptr = 20;            //Dereference that pointer, 
                          // and assign a value to random memory address.
                          //Depending on external (not inside your program) state
                          // this will either crash or SILENTLY CORRUPT another 
                          // data structure in your program.  

    printf("%d", *ptr);   //Print contents of same random memory address
                          // May or may not crash, depending on who owns this address

    return 0;             
}

Second Program with comments

第二个程序与评论

#include <stdio.h>

int main(){
    int *ptr;              //Create pointer to random memory address

    int q = 50;            //Create local variable with contents int 50

    ptr = &q;              //Update address targeted by above created pointer to point
                           // to local variable your program properly created

    printf("%d", *ptr);    //Happily print the contents of said local variable (q)
    return 0;
}

The key is you cannot use a pointer until you know it is assigned to an address that you yourself have managed, either by pointing it at another variable you created or to the result of a malloc call.

关键是您不能使用指针,除非您知道它被分配到您自己管理的地址,或者通过指向您创建的另一个变量或malloc调用的结果来指定它。

Using it before is creating code that depends on uninitialized memory which will at best crash but at worst work sometimes, because the random memory address happens to be inside the memory space your program already owns. God help you if it overwrites a data structure you are using elsewhere in your program.

使用它之前,是创建依赖于未初始化内存的代码,它将在最好的情况下崩溃,但有时在最坏的情况下会发生,因为随机内存地址恰好位于您的程序已经拥有的内存空间内。如果它覆盖了程序中其他地方的数据结构,那么上帝会帮助您。

#3


1  

In the first example, ptr has not been initialized, so it points to an unspecified memory location. When you assign something to this unspecified location, your program blows up.

在第一个示例中,ptr尚未初始化,因此它指向一个未指定的内存位置。当你给这个未指定的位置分配一些东西时,你的程序就会爆炸。

In the second example, the address is set when you say ptr = &q, so you're OK.

在第二个例子中,当你说ptr = &q时,地址是设置的,所以你可以。

#1


26  

The problem is that you're not initializing the pointer. You've created a pointer to "anywhere you want"—which could be the address of some other variable, or the middle of your code, or some memory that isn't mapped at all.

问题是您没有初始化指针。您已经创建了一个指向“您想要的任何地方”的指针——它可能是某个其他变量的地址,或者是代码的中间部分,或者是一些根本没有映射的内存。

You need to create an int variable somewhere in memory for the int * variable to point at.

您需要在内存中为int *变量创建一个int变量。

Your second example does this, but it does other things that aren't relevant here. Here's the simplest thing you need to do:

第二个例子是这样的,但它做的其他事情与这里无关。下面是你需要做的最简单的事情:

int main(){
    int variable;
    int *ptr = &variable;
    *ptr = 20;
    printf("%d", *ptr);
    return 0;
}

Here, the int variable isn't initialized—but that's fine, because you're just going to replace whatever value was there with 20. The key is that the pointer is initialized to point to the variable. In fact, you could just allocate some raw memory to point to, if you want:

这里,int变量不是初始化的,但这很好,因为你只需要用20来替换所有的值。关键是指针被初始化以指向变量。事实上,你可以分配一些原始内存来指向,如果你想:

int main(){
    void *memory = malloc(sizeof(int));
    int *ptr = (int *)memory;
    *ptr = 20;
    printf("%d", *ptr);
    free(memory);
    return 0;
}

#2


7  

First Program with comments

第一个程序与评论

#include <stdio.h>

int main(){
    int *ptr;             //Create a pointer that points to random memory address

    *ptr = 20;            //Dereference that pointer, 
                          // and assign a value to random memory address.
                          //Depending on external (not inside your program) state
                          // this will either crash or SILENTLY CORRUPT another 
                          // data structure in your program.  

    printf("%d", *ptr);   //Print contents of same random memory address
                          // May or may not crash, depending on who owns this address

    return 0;             
}

Second Program with comments

第二个程序与评论

#include <stdio.h>

int main(){
    int *ptr;              //Create pointer to random memory address

    int q = 50;            //Create local variable with contents int 50

    ptr = &q;              //Update address targeted by above created pointer to point
                           // to local variable your program properly created

    printf("%d", *ptr);    //Happily print the contents of said local variable (q)
    return 0;
}

The key is you cannot use a pointer until you know it is assigned to an address that you yourself have managed, either by pointing it at another variable you created or to the result of a malloc call.

关键是您不能使用指针,除非您知道它被分配到您自己管理的地址,或者通过指向您创建的另一个变量或malloc调用的结果来指定它。

Using it before is creating code that depends on uninitialized memory which will at best crash but at worst work sometimes, because the random memory address happens to be inside the memory space your program already owns. God help you if it overwrites a data structure you are using elsewhere in your program.

使用它之前,是创建依赖于未初始化内存的代码,它将在最好的情况下崩溃,但有时在最坏的情况下会发生,因为随机内存地址恰好位于您的程序已经拥有的内存空间内。如果它覆盖了程序中其他地方的数据结构,那么上帝会帮助您。

#3


1  

In the first example, ptr has not been initialized, so it points to an unspecified memory location. When you assign something to this unspecified location, your program blows up.

在第一个示例中,ptr尚未初始化,因此它指向一个未指定的内存位置。当你给这个未指定的位置分配一些东西时,你的程序就会爆炸。

In the second example, the address is set when you say ptr = &q, so you're OK.

在第二个例子中,当你说ptr = &q时,地址是设置的,所以你可以。