开发者

in C what is the proper way to pass a pointer to a string from a function to the main

this is the rough idea of what I am trying to do: I want the pointer in main to point to the word I just in my function.

my actual code is very long so please excuse this format.

main()
{
char *word;
int lim 256;
*word = function(word,li开发者_StackOverflow中文版m)//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
}


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;
}

Functions used in the sample code above:

malloc free

This seems like a decent tutorial: C Tutorial – The functions malloc and free


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

int main()
{
    char* word = func();
    free(word);
    return 0;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜