c++ - 将指针作为输出参数传递给函数
问题描述
我使用“pBuff”作为指针并将一个字符数组放入函数“myfunc”中。所以,在主函数中,我应该在 aBuff 中接收它。
但它不起作用..这里有什么问题?
#include <stdio.h>
void myfunc(void *pBuff, int &i);
int main()
{
int len;
char aBuff[2]={0};
printf("Hello World");
myfunc(aBuff,len);
printf("aBuff %s", aBuff);
return 0;
}
myfunc(void *pBuff, int &i){
char a[2] = {'a', 'b'};
i = 5;
pBuff = &a;
}
char a[]
应该作为主函数中的输出参数
解决方案
您正在传递一个指向您的函数的指针,在您的函数内部,您将临时变量的地址分配a
给该pBuff
变量。原始aBuff
变量不受影响。
当我们使用 c++ 时,使用字符串的更简单的解决方案是:
#include <iostream>
void myfunc(std::string& pBuff, int &i);
int main()
{
int len;
std::string aBuff;
std::cout << "Hello World";
myfunc(aBuff,len);
std::cout << "aBuff " << aBuff;
return 0;
}
void myfunc(std::string& pBuff, int &i){
pBuff = "ab";
i = 5;
}
如果你真的必须使用原始字符数组,那么这将是实现它的一种方法(注意删除 ,void*
这里没有理由使用它):
myfunc(char *pBuff, int &i){
strcpy(pBuff, "ab");
i = 5;
}
如果您需要在aBuff
数组中存储 2 个字符,则它需要 3 个字符而不是 2 个字符,因为您需要为空终止符留出空间,否则printf
其他字符串函数将无法正常工作。
推荐阅读
- c# - System.Runtime.InteropServices.COMException 类型不匹配。尝试使用数据创建 xls 文件时出错
- javascript - TypeError:从调用中收集用户输入时,无法读取 twilio 中未定义的属性“数字”
- javascript - 为文件夹中的每个文件制作一个下载按钮
- java - JAXB:从不同继承级别获取标签
- oracle - ORA-00936: 缺少使用 SELECT INTO local_variable 的表达式
- mysql - 触发更新同一张表
- bash - Passing bc into a variable isn't working right for me in Bash
- javascript - 如何使用 jquery 隐藏特定的 json 对象数据
- css - box-sizing:border-box; 是什么意思?在网站上做?
- git - Github Action 拉取请求不提供 github_sha 的最后一次提交