c++ - 理解指针和本地范围

标签 c++ c pointers

<分区>

假设我有以下功能:

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 是局部范围。

第二个 printf 打印正确的值,blah = blah 的地址,*blah = 5

为什么局部作用域只影响处理数组的 allocateMemory,而不影响整数?

为什么第一个 printf(返回 char* )打印随机值并受局部作用域影响,但第二个(返回 int* )不受影响?

最佳答案

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

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
}

关于c++ - 理解指针和本地范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28272271/

相关文章:

c++ - 是否可以将运算符用作映射中的映射值?

c - Mongo c driver find查询错误处理

python - 删除文件的任意 block

c - 如何警告指向超出范围的局部变量的指针

c++ - 如何从 dll 中调用函数?

c++ - Any Time 函数保证调用返回不同的值

c++ - 调用模板函数时的意外输出

c++ - 为什么 std::string::find() 可以处理 '\0' ?

c - 为什么要用一个变量的地址来乘以另一个变量?

c++ - 在堆上初始化的指针数据成员