简体   繁体   English

以下代码段的输出是什么?

[英]what will be the output of the following snippet?

what's happening after clrscr? clrscr之后发生了什么事?

#include<stdio.h>
#include<conio.h>
int *call();
void main()
{
int *ptr;
ptr=call();
clrscr();
printf("%d",*ptr);
getch();
}  

int*call()
{
int a=25;
a++;
return &a;
}

output:
-10

code works like this: call() is called, a=25, then a=26. 代码是这样的: call()被调用,a = 25,然后a = 26。 let address of a be 65518. this address is returned to ptr. 设a的地址为65518。此地址返回给ptr。 since return type is int, instead of 65518, (due to cyclic property) -18 is returned. 由于返回类型为int,而不是65518,(由于循环属性)将返回-18。 so ptr=&a=-18. 所以ptr =&a = -18。 then clrscr clears it....but how *ptr is printed as output? 然后clrscr清除它。...但是如何将*ptr打印为输出? i mean address cannot be negative(-18). 我的意思是地址不能为负(-18)。

Returning a pointer to local is undefined behavior. 返回本地指针是未定义的行为。 Anything could happen - your program could crash, but more likely it is going to print some arbitrary number. 可能会发生任何事情-您的程序可能会崩溃,但更有可能它将打印一些任意数字。

If you need to return a pointer from a C function, you need to either allocate a memory block in the dynamic storage, like this: 如果需要从C函数返回指针,则需要在动态存储中分配一个内存块,如下所示:

int*call()
{
    int *a=malloc(sizeof(int));
    *a = 25;
    *a++;
    return a;
}

or use a pointer to a statically allocated block, like this: 或使用指向静态分配块的指针,如下所示:

int* call()
{
    static int a=25;
    a++;
    return &a;
}

If you choose the dynamic allocation route, the caller must free the pointer returned by your function. 如果选择动态分配路由,则调用者必须释放函数返回的指针。

int*call()
{
int a=25; // <--- use malloc here i.e. int a = malloc(sizeof(int)); then you can set a value to a and return the pointer without any problemk, OTHERWISE => it will return an address of some random junks you don't want, its gonna be completely random
a++;
return &a;
}

When call() is called, a new stack frame is created with space for the local variable a , which has its lifetime during the execution of call() . call() ,将为局部变量a创建一个新的堆栈框架,并为其留a空间,局部变量a在执行call()期间具有生命周期。 When it returns, the stack frame is removed along with its local variable(s) and data. 返回时,将删除堆栈帧及其局部变量和数据。 Trying to use this data outside the function is undefined, because it no longer exists, logically. 尝试在函数外部使用此数据是未定义的,因为从逻辑上讲它不再存在。

If you want to declare a inside a function and use it afterwards, you'll need to allocate it: 如果要声明a函数内部,之后使用它,你需要将它分配:

... 
int *a = malloc(sizeof int);
*a = 26;
return a;
... 

Remember to free() this pointer after you're finished using it. 使用完该指针后,请记住将其free()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM