【发布时间】:2010-04-01 10:17:30
【问题描述】:
我必须定义一个接口。我作业中的API如下:
int generate_codes(char * ssn, char * student_id);
int 表示通过或失败的 0 或 1。 studentid 是一个输出参数,应该返回一个 6 位数的 id。 ssn 是一个 9 位的输入参数
他们的学校计划将采用 ssn 并使用我的代码生成学生 ID。
- 现在从 API 的角度来看,我不应该对两个参数都使用 const char *。
- 不应该通过引用传递studentid吗?而不是指针?
- 谁能告诉我如何在我的测试应用程序中轻松使用指针,该应用程序使用我的 api 来获取指针,以便从 char * 打印 std::string?
我的应用代码看起来像
const char * ssn = "987098765"
const char * studnt_id = new char [7];
int value = -1;
value = generate_codes(ssn,studnt_id);
std::string test(studnt_id);
std::cout<<"student id= "<<test<<" Pass/fail= "<<value<<std::endl;
delete [] studnt_id;
return 0;
我基本上得到了一个关于
std::cout<<"student id= "<<test.c_str()<<" Pass/fail= "<<value<<std::endl;
然后它起作用了,但我得到了价值的垃圾。不知道如何从指针中获取值。函数内的值打印得很好。但是当我尝试在函数之外打印它时,它会打印垃圾。在上面的函数中,我确实设置了 studndt_id
std::string str_studnt_id = studnt_id;
这是将字符串参数带入执行代码生成的真正功能。 当我准备好代码并想要返回它时,我会执行以下操作:
studnt_id = str_studnt_id.c_str();
是否应该使 str_studnt 的地址指向 studnt_id 的地址,因此我对其指向它的值所做的任何更改都应该反映在函数之外?此 API 使用 char *,但我的函数使用 std::string。
【问题讨论】:
-
API 指定 char* 的事实并不意味着您不能更改该接口。只是提议改变它。这避免了您必须包装它并为非常简单的事情创建不必要的复杂性。
标签: c++