我的“追加”算法或代码出了什么问题?

时间:2014-05-29 00:27:51

标签: c

给出了2个字符串,第二个字将附加到第一个字符串,第三个变量将存储该字符串。例如;

char *str1 = "abc";
char *str2 = "def";
char *str3 = "abcdef"; //should be

这是我的代码,我收到运行时错误:

#include <stdio.h>
#include <malloc.h>

void append(char *str1, char *str2, char *str3, int size1, int size2)
{
    int i=0;
    str3 = (char*) malloc(size1+size2+1);
    str3 = str1;

    while (str2[i] != '\0') {
        str3[i+size1] = str2[i];
        i++;
    }

    str3[size1+size2] = '\0';
}

int main() 
{
    char *str1 = "abc";
    char *str2 = "def";
    char *str3;

    append(str1, str2, str3, 3, 3);

    return 0;
}

3 个答案:

答案 0 :(得分:2)

str3 = (char*) malloc(size1+size2+1);
str3 = str1;

这是你的问题。这样做会将指针替换为从malloc到包含str1的指针的正确空间量。保持您的循环设计,将其更改为:

str3 = malloc(size1+size2+1); 
for (int j = 0; str1[j] != '\0'; j++)
    str3[j] = str1[j];

另外,请参阅此问题/答案,了解如何在C中投射malloc的结果: Do I cast the result of malloc?

答案 1 :(得分:0)

代码还有另一个问题。您可以按值传递指针。因此,函数内的任何malloc都只会进行局部更改。函数结束后,指针仍将指向旧值。如果要更改它,应该将指针传递给指针。查看示例:

#include <stdio.h>
char *c = "Second";
void assign(char *s) { s = c; }

int main() 
{
    char *str = "First";
    assign(str);
    printf("String after assign: %s\n", str);
    return 0;
}

运行该程序后,您将看到“第一个&#39;在你的控制台。正确的代码是:

#include <stdio.h>
char *c = "Second";
void assign(char **s) { *s = c; }

int main() 
{
    char *str = "First";
    assign(&str);
    printf("String after assign: %s\n", str);
    return 0;
}

答案 2 :(得分:0)

#include <stdio.h>
#include <stdlib.h> //to standard
#include <string.h>

char *append(const char *str1, const char *str2, int size1, int size2){
//parameter char *str3 is local variable.
//It is not possible to change the pointer of the original.
//str3 = str1;//<<-- memory leak
//str3[i+size1] = str2[i];//<<-- write to after str1(can't write!)

    char *str3 = (char*) malloc(size1+size2+1);
    memcpy(str3, str1, size1);//copy to alloc'd memory.
    memcpy(str3 + size1, str2, size2);//copy to after str1
    str3[size1+size2] = '\0';
    return str3;
}

int main(){
    char *str1 = "abc";
    char *str2 = "def";
    char *str3;

    str3 = append(str1, str2, 3, 3);
    printf("%s\n", str3);

    return 0;
}