直接给 C 指针赋值 [英] Directly assigning values to C Pointers

查看:37
本文介绍了直接给 C 指针赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始学习 C,并且一直在使用 MinGW for Windows 运行一些简单的程序,以了解指针的工作原理.我尝试了以下方法:

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:

#include <stdio.h>

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

哪个编译正确,但是当我运行可执行文件时它不起作用 - 该值没有打印到命令行,而是收到一条错误消息,指出 .exe 文件已停止工作.

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.

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

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

#include <stdio.h>

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

效果很好.

我的问题是,为什么我不能直接为指针设置文字值?我在网上查看了一些教程以获取指针,大多数教程的做法与第二个示例相同.

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.

感谢任何帮助.

推荐答案

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

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.

您需要在内存中的某处创建一个 int 变量,以便 int * 变量指向.

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

您的第二个示例执行此操作,但它执行的其他操作与此处无关.这是您需要做的最简单的事情:

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;
}

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

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 main(){
    void *memory = malloc(sizeof(int));
    int *ptr = (int *)memory;
    *ptr = 20;
    printf("%d", *ptr);
    free(memory);
    return 0;
}

这篇关于直接给 C 指针赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆