这是我想做的事情的粗略想法: 我希望 main 中的指针指向函数中的“I”。
我的实际代码很长,请原谅这种格式。
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
}
最佳答案
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;
}
上面示例代码中使用的函数:
这似乎是一个不错的教程: C Tutorial – The functions malloc and free
关于c - 在C中,将指向字符串的指针从函数传递到主函数的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4020543/