c - 在C中,将指向字符串的指针从函数传递到主函数的正确方法是什么

标签 c string pointers

这是我想做的事情的粗略想法: 我希望 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;
}

上面示例代码中使用的函数:

malloc free

这似乎是一个不错的教程: C Tutorial – The functions malloc and free

关于c - 在C中,将指向字符串的指针从函数传递到主函数的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4020543/

相关文章:

c - 执行thread_kill时出现segmentation fault

c - 指向函数错误的指针

c++ - OpenCV 如何处理 Mat 作为指针来加速代码?

c++ - 为什么我可以在 C 中将 int 文字隐式转换为 int * 而在 C++ 中却不能?

c - 使用节点地址的链表大小

php - 由逗号和新行一起展开

java - 修剪字符串并检查字符串是否不为空

Python:如何只保留字符串的前 50 个字符

c++ - 指针重新分配和多态性

c - 在 C 中映射非顺序值的最佳方法