[英]what will be the output of the following snippet?
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
代碼是這樣的: call()
被調用,a = 25,然后a = 26。 設a的地址為65518。此地址返回給ptr。 由於返回類型為int,而不是65518,(由於循環屬性)將返回-18。 所以ptr =&a = -18。 然后clrscr清除它。...但是如何將*ptr
打印為輸出? 我的意思是地址不能為負(-18)。
返回本地指針是未定義的行為。 可能會發生任何事情-您的程序可能會崩潰,但更有可能它將打印一些任意數字。
如果需要從C函數返回指針,則需要在動態存儲中分配一個內存塊,如下所示:
int*call()
{
int *a=malloc(sizeof(int));
*a = 25;
*a++;
return a;
}
或使用指向靜態分配塊的指針,如下所示:
int* call()
{
static int a=25;
a++;
return &a;
}
如果選擇動態分配路由,則調用者必須釋放函數返回的指針。
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;
}
call()
,將為局部變量a
創建一個新的堆棧框架,並為其留a
空間,局部變量a
在執行call()
期間具有生命周期。 返回時,將刪除堆棧幀及其局部變量和數據。 嘗試在函數外部使用此數據是未定義的,因為從邏輯上講它不再存在。
如果要聲明a
函數內部,之后使用它,你需要將它分配:
...
int *a = malloc(sizeof int);
*a = 26;
return a;
...
使用完該指針后,請記住將其free()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.