【发布时间】:2013-04-08 17:53:32
【问题描述】:
我有这个结构:
struct student {
int id;
string name;
string surname;
};
我需要做的是用这个声明来做函数:
char* surname_name (student Student)
它将格式化我输入的每个学生的格式,如“姓,名”,它会带回指向它的指针。
到目前为止,我所做的是:
char* surname_name (student Student){
char *pointer= (char*) malloc (sizeof(char)*(Student.name.length + Student.surname.length + 2)); // + 2 because of space and comma
string::iterator it;
int i=0;
for (it= Student.surname.begin(); it != Student.surname.end(); it++){
(*pointer)[i] = it; // here it gives me error
}
... // here still should be added code for comma, space and name
return pointer;
}
无论如何我都做不到,因为在任务中函数需要有这个声明。如何正确地做到这一点?
【问题讨论】:
-
你真的需要
char*吗?std::string不是更好吗?如果您需要这样,我建议将char*作为参数,让用户将自己分配的缓冲区传递给。 -
是的,我肯定会立即使用它,但我不能。需要使用这个,因为稍后我需要制作其他函数,它将这个函数作为参数,所以我不能修改声明。
-
你不能返回一个
std::string,然后使用c_str成员函数将它作为char*来获取吗? -
您可以在一个字符串中进行连接,然后您可以只 malloc 一些内存,将字符串 memcopy 到其中,然后返回。这样会容易得多。
标签: c++ pointers memory-management character