更改函数中的字符串

时间:2013-12-08 13:32:53

标签: c string function pointers

如果我有这种功能:str1 = NULL在开始

 Result dosomething(char* str1, char* str){
    str1=malloc(strlen(str2)+1); //followed by NULL check
    strcpy(str1, str2);
    .
    .
 return something

然后我在其他功能中使用此功能:

 char* output="hello";
 char* input=NULL;
 result=dosomething(input,output);

由于某种原因输入在使用“dosomething”函数后仍然为NULL,尽管如果我在strcpy之后使用printf,我可以看到str1确实变为“hello”。我在将char *传递给其他函数时,我在做错了吗?

3 个答案:

答案 0 :(得分:3)

您需要将指针传递给您想要更改的字符串

Result dosomething(char** str1, char* str){
    *str1=malloc(strlen(str2)+1); //followed by NULL check
    strcpy(*str1, str2);

呼叫

result=dosomething(&input,output);

或更改函数以返回新分配的字符串,返回NULL以指示错误

char* dosomething(char* str){
    char* str1=malloc(strlen(str2)+1); //followed by NULL check
    strcpy(str1, str2);
    ...
    return str1;

呼叫

input=dosomething(output);
if (input==NULL) {
    // error

答案 1 :(得分:0)

通过指针将字符串传递给指针

Result dosomething(char** str1, char* str){
    *str1=malloc(strlen(str2)+1); //followed by NULL check
    strcpy(*str1, str2);

并用作

result=dosomething(&input,output);

因为你需要修改指针的值,所以传递它的地址。

答案 2 :(得分:0)

你正在绊倒,因为你正在改变你在函数内部传递的指针的值。为了便于说明,请使用char*替换int此处,看看出了什么问题:

Result dosomething_int(int a, int b) {
    a = 29;
    ...
}

此处29代替您的malloc调用,该调用将使用新值替换您传递的str1指针的值。现在使用此功能:

int output = 17;
int intput = 0;
result = dosomething_int(input,output);

您希望此后input的值为0或29吗?可能你很容易回答这个问题 - 同样的事情发生在char *案例中。您需要将指针传递给char *来解决它:

Result dosomething(char** str1, char * str2) {
    *str1 = malloc(...);
    ...
}