直接将值分配给C指针 [英] Directly assigning values to C Pointers

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

问题描述

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

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替换那里的任何值.关键是 pointer 初始化为指向variable.实际上,如果需要,您可以分配一些原始内存以指向该对象:

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天全站免登陆