取消引用指针,而不会在一个变量指向他们 [英] Dereferencing pointers without pointing them at a variable

查看:152
本文介绍了取消引用指针,而不会在一个变量指向他们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解一些指点如何工作。我一直以为,当你创建了一个指针变量(P),你不能尊重并分配(* P =值),除非你要么malloc分配空间,它(P =的malloc(X)),或者将其设置为另一个变量的地址(p =安培; A)

不过,在这个code,第一个任务都能正常工作,而最后一个会导致​​段错误:

  typedef结构
{
    int值;
} test_struct;INT主要(无效)
{
    //这工作
    INT *科林;
    *科林= 5;    //这永远不会奏效
    test_struct *卡特;
    carter->值= 5;
}

为什么当科林不指向任何备用内存的第一个工作? ?为什么2号从来没有工作?

我用C写这个,但人们用C ++知识应该能够回答这一点。

编辑:好吧,我得到第一个应该不能工作,但为什么它的。这就是我了。


解决方案

  //这个作品
INT *科林;
*科林= 5;

欢迎未定义行为的事实:它不会崩溃,并不意味着它的作品。访问未初始化的指针永远是错的,但有时它不会崩溃。


  

未能尊重和分配,除非你,要么malloc分配空间,或将其设置为另一个变量的地址


这是正确的。一般情况下,您需要将您的指针指向已分配给你的程序的某个地方。有这样做的多种方法,但他们都归结到你所描述的两种场景之一 - 指针指向要么一个动态分配的内存(即的malloc ) ,或者静态分配的内存(即一个变量)。

I'm having trouble understanding how some pointers work. I always thought that when you created a pointer variable (p), you couldn't deference and assign (*p = value) unless you either malloc'd space for it (p = malloc(x)), or set it to the address of another variable (p = &a)

However in this code, the first assignment works consistently, while the last one causes a segfault:

typedef struct
{
    int value;
} test_struct;

int main(void)
{
    //This works
    int* colin;
    *colin = 5;

    //This never works
    test_struct* carter;
    carter->value = 5;
}

Why does the first one work when colin isn't pointing at any spare memory? And why does the 2nd never work?

I'm writing this in C, but people with C++ knowledge should be able to answer this as well.

Edit: Okay I get that the first one shouldn't work either, but why does it. That's what I'm after.

解决方案

// This works
int* colin;
*colin = 5;

Welcome to undefined behavior: the fact that it does not crash does not mean that it works. Accessing uninitialized pointer is always wrong, yet sometimes it does not crash.

couldn't deference and assign unless you either malloc'd space for it or set it to the address of another variable

This is correct. In general, you need to point your pointer to some place that has been allocated to your program. There are multiple ways of doing that, but they all boil down to one of the two scenarios that you describe - the pointer is pointed either to a dynamically allocated memory (i.e. malloc), or to statically allocated memory (i.e. a variable).

这篇关于取消引用指针,而不会在一个变量指向他们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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