如何在分配后用字符串填充char?

时间:2013-04-08 17:53:32

标签: c++ pointers memory-management character

我有这个结构:

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;
}

我无论如何都无法做到,因为在任务中,函数需要具有此声明。如何做到这一点?

3 个答案:

答案 0 :(得分:1)

(*pointer)[i] = it;

应该是

*(pointer+i) = *it; //assigning the current char to correct position

你也应该正确地增加i

您也可以使用std::string进行简单连接。

答案 1 :(得分:1)

这应该可以解决问题:

char * surname_name (student Student){
    return strdup((Student.surname + ", " + Student.name).c_str());
}

答案 2 :(得分:1)

我更喜欢使用std::string::c_str

string surname_name (const student &Student)
{
    return Student.name + " " + Student.surname;
}

// ...

do_something( surname_name(student).c_str() );

如果你真的想要返回指针,可以按照以下方式执行:

char *surname_name (const student &Student)
{
    string s = Student.name + " " + Student.surname;
    char *p = new char [s.length()+1];
    strcpy(p, s.c_str());
    return p;
}

不要忘记delete返回的指针。