2010-10-26 44 views
2

這是我想要做的事情的粗略想法: 我想在主要指針指向單詞我只是在我的功能。在C什麼是正確的方式來傳遞一個指針字符串從一個函數到主

我的實際代碼很長,所以請原諒這種格式。在上面的示例代碼中使用

main() 
{ 
char *word; 
int lim 256; 
*word = function(word,lim)//I am not returning the address back only the first letter 
} 

function(word,lim) 
{ 
//memory allocation 
//getting word 
//reset address 
return(*word);//I am passing the correct address here 
} 
+0

此代碼將無法編譯通過一次遠射,並且我不清楚這個詞的記憶來自哪裏? – EboMike 2010-10-26 03:47:56

+0

如果您將指針作爲參數之一傳遞,那麼爲什麼您需要從函數返回相同的指針? – Alam 2010-10-26 03:48:52

+0

是的,它不應該編譯。我關心的是如何正確地將指針從函數傳遞給主函數。內存只是一個單詞=(char *)malloc(256 * sizeof(char *)) – pisfire 2010-10-26 03:50:43

回答

3
char* allocate_word(int lim) 
{ 
    // malloc returns a "void*" which you cast to "char*" and 
    //return to the "word" variable in "main()" 
    // We need to allocate "lim" number of "char"s. 
    // So we need to multiply the number of "char"s we need by 
    //the number of bytes each "char" needs which is given by "sizeof(char)". 
    return (char*)malloc(lim*sizeof(char)); 
} 

int main() 
{ 
char *word; 
// You need to use "=" to assign values to variables. 
const int lim = 256; 
word = allocate_word(lim); 
// Deallocate! 
free(word); 

return 0; 
} 

功能:

malloc free

這似乎是一個不錯的教程: C Tutorial – The functions malloc and free

+0

這不是一個好方法 - 你在函數中分配內存,並要求調用者(主函數)釋放分配的內存。一般而言,這種方法會導致內存泄漏。正確的做法留給讀者作爲練習。 – 2010-10-26 03:54:05

+0

@大衛:我明白。但這是OP想要完成的。 – Jacob 2010-10-26 03:56:58

+0

@Zack - 我只會在函數名中明確聲明如「AllocateWord()」,並且最好只有當您有一個匹配的「FreeWord()」函數時纔會這樣做。否則,內存泄漏的風險太大了。 – EboMike 2010-10-26 03:59:32

0
char* func() 
{ 
    return (char*)malloc(256); 
} 

int main() 
{ 
    char* word = func(); 
    free(word); 
    return 0; 
} 
相關問題