2015-06-20 246 views
-2

我的C函數代碼不斷給我錯誤,我不知道什麼是錯的。C代碼奇怪(指針)

int * myfunc(int a) 
{ 
    int * newNum, i; 
    i = a*a; 
    *newNum = i; 
    return newNum; 
} 
+0

'newNum'需要的地方點...... – Diego

+0

這篇文章可能會幫助你:http://stackoverflow.com/questions/1224042/returning-a-pointer-to-an-automatic-variable –

+0

返回懸掛指針;-)自動變量我在myfunc返回後超出範圍。 –

回答

2

有三種類型的內存或變量,像在你的函數中一樣自動,靜態和手動。自動持續,範圍持續。靜態是,如果你聲明它是靜態的:

static int i; 

它活着,而程序還活着。像全局變量一樣。最後手動使用malloc並自由分配和釋放內存。當然,你想要分配變量的地址返回前指針,像這樣:

int * newPointer = &i; 

如果變量是靜態的,將保持值通過函數調用。 代碼避免了編譯器警告有關通過指定的局部變量的地址指針,以便返回局部變量的地址,它可能是在其上運行某種像皮棉或夾板工具的好主意,這裏是對這種tools

+1

您應該詳細說明上述如何幫助OP。 – Carcigenicate

+1

'malloc()'和朋友管理_dynamically allocated_ memory,aka ** heap **。所有命名變量都必須「手動」定義,編譯器只能「自動」處理臨時數據。這不是「靜態的」,而是全球性的,具有不同的聯繫。 – Olaf

+0

@Olaf當然,這裏的問題是他正在聲明指針,並將局部變量的地址賦值給指針,這是避免編譯器'函數返回局部變量地址'的警告的好方法。尋找可以對代碼進行靜態分析並在這種情況下提供幫助的工具。 –

1

看討論,newNum指針整數。所以newNum的目的是保存整數address

當你宣佈

int * newNum; 

newNum然後指着一些垃圾。

以下各行,

*newNum = i; 

newNum內容將通過i被更新。但你忘了,newNum擁有一些垃圾地址?因此i的值被分配一些垃圾location

你可以試試這個:

/** 
* The following function will take an integer pointer from the caller. 
* Its callers duty to check whether the pointer is initialed or not. 
*/ 
void myfunc(int * newNum) { 
    // the content of the newNum pointer points will be updated 
    // as the memory address is sent here, we need not to return anything 
    *newNum = (*newNum) * (*newNum); 
} 

int main() { 
    int someInteger = 4; 
    int *ptr = &someInteger; 
    myfunc(ptr); 
    printf("Content of the pointer: %d", *ptr); 
    return 0; 
} 

你會得到輸出一樣,

內容指針:16

+0

@Blastfurnace,我錯過了標記! Ty,編輯了我的答案。 –