search

Home  >  Q&A  >  body text

c++ - C语言程序小问题,本人小白刚学C

代码1:当a是变量时

#include<stdio.h>

int * ccc();

int main(void)

{
    int* p = ccc();
    
    printf("%d\n",*p);
    printf("%d\n",*p);
    printf("%d\n",*p);
    printf("%d\n",*p);
    printf("%d\n",*p);
    return 0;
}

int * ccc()

{
    int a = 5;
    
    return &a;

}

运行结果:

代码2:当变量时数组时

#include<stdio.h>

int * ccc();

int main(void)

{
    int i;
    int* p = ccc();
    
    for(i = 0;i <= 5;i++)
    {
        printf("%d ",*(p + i));
    }
    return 0;
}

int * ccc()

{
    int a[6] = {1,2,3,4,5,6};
    int * p = a;
    
    return p;

}

运行结果:

小白疑问
1.为什么运行结果会是这样的?为啥局部变量a被释放了第一次还能正常访问,而且为什么只有第一次能正常访问呢,空间不是都被释放了吗?变量为数组是为啥运行结果是这样的?好奇怪,我想知道具体的原理

谢谢各位大神了哈O(∩_∩)O

高洛峰高洛峰2772 days ago396

reply all(2)I'll reply

  • 天蓬老师

    天蓬老师2017-04-17 15:28:21

    That’s it.
    Local variables are stored in the stack area, and every time the stack is operated, the pointer on the top of the stack is moved instead of wasting time and effort to reset the abandoned stack memory. In other words, when the function returns, the value Still there. However, function jumps will also use stack space, so some data will be changed when the CPU makes function jumps. The reason why the first number does not change but does change after that is probably because when the jump that occurs when the printf function is called, only the stack space after the first number is used.
    If you define a particularly large array in your structure, and then use the same method to type out the information in the first structure, no surprise, the second half of the array in the first structure Parts will also change.

    reply
    0
  • 迷茫

    迷茫2017-04-17 15:28:21

    The students above have answered clearly.
    But it is still recommended that you debug and look at the address space, so that it will be clearer. Then Chapter 1 or Chapter 2 of "In-depth Understanding of Computer Systems" will explain it in more detail. If you take a look at it together, you won’t be bothered anymore.

    reply
    0
  • Cancelreply