views:

87

answers:

2

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,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
}
+3  A: 
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

Jacob
This is not a good approach -- you're allocating memory in the function and requiring the caller (the main function) to release the allocated memory. This approach, in general, will lead to memory leaks. The correct approach is left as an exercise for the reader.
David Harris
@David: I understand. But this is what the OP was trying to accomplish.
Jacob
Sometimes - actually, quite often - "this function allocates memory and transfers ownership of that memory to its caller" IS the correct approach.
Zack
@Zack - I would only ever do that in functions that explicitly state that in their function name, like "AllocateWord()", and even then preferably only if you have a matching "FreeWord()" function. Otherwise, the risk of memory leaks is just too great.
EboMike
Even if this is a requirement of the homework, it is much better for beginners to learn correct techniques from the start and not have to unlearn them later.
David Harris
Don't cast the result of `malloc` in C, do check for it returning `NULL`. `sizeof (char)` is always 1 so redundant.
schot
A: 
char* func()
{
    return (char*)malloc(256);
}

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