了解指针和局部范围内 [英] Understanding pointers and local scope

查看:90
本文介绍了了解指针和局部范围内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下功能:

char* allocateMemory() 
{
    char str[20] = "Hello world.";
    return str;
}

int* another()
{
    int x = 5;
    return &x;
}

int _tmain(int argc, _TCHAR* argv[])
{
    char* pString = allocateMemory();
    printf("%s\n", pString);

    int* blah = another();
    printf("%d %d \n", blah, *blah);

    return 0;
}

第一个printf打印随机值,因为str是本地作用域。

The first printf prints random values, because str IS LOCAL SCOPE.

第二个printf打印出正确的价值观,有嗒嗒=嗒嗒的地址,*等等= 5

The second printf prints the proper values, with blah = address of blah, *blah = 5

为什么本地范围仅影响allocateMemory它与数组的交易,而不是整数?

Why is it that local scope only affects allocateMemory which deals with arrays, but not integer?

为什么第一个printf(返回的char *)打印随机值,由局部范围内的影响,但不是第二个(返回int *)?

Why does the first printf (returning char* ) prints random values and is affected by local scope, but not the second one (returning int* )?

推荐答案

访问这超出范围是未定义行为的方法的局部变量的两种方式。这些都是一些有效的方式:

Both ways of accessing the local variables of a method which goes out of scope is Undefined Behavior. These are some valid ways:

char* allocateMemory() 
{
    char* str= malloc(sizeof(char) * 20); //assuming C
    strcpy(str, "Hello World.");
    return str; //Valid 
}

const char* allocateMemory() 
{
    return "Hello world."; //Valid Hello World is in read only location
}

int* another()
{
    int *x = malloc(sizeof(int)); //assuming C
    *x = 5;
    return x; //Valid
}

这篇关于了解指针和局部范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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