C语言 直接给 C 指针赋值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17665793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:54:42  来源:igfitidea点击:

Directly assigning values to C Pointers

cpointers

提问by Shreya Srinivas

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 for Windows 运行一些简单的程序,以了解指针的工作原理。我尝试了以下方法:

#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.

任何帮助表示赞赏。

回答by abarnert

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 intvariable 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 intvariable 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 pointeris initialized to point to the variable. In fact, you could just allocate some raw memory to point to, if you want:

在这里,int变量没有被初始化——但这没关系,因为你只是要用20. 关键是指针被初始化为指向variable. 事实上,如果你愿意,你可以只分配一些原始内存来指向:

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

回答by JonnyRo

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.

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

回答by jsp

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 时设置了地址,所以您没问题。