【发布时间】:2014-02-07 21:42:53
【问题描述】:
我将目标的大小定义为 string1 的大小。然后我将 string2 添加到目标。我没有增加目标的大小。为什么我的静止代码有效?
char *string1 = "this is a ";
char *target = malloc(sizeof(string1)); // if i don't do this, code gives error.
strcpy(target, string1);
printf("%s\n", target);
char *string2 = "string";
strcat(target, string2); // how come I don't need to call malloc again?
printf("%s\n", target); // works
我在 Mac 上用 Xcode 编译了这个。
【问题讨论】:
-
你的代码从头到尾都是错误的。
-
sizeof(string1) 为 4(取决于机器),因为指针存储为整数。
-
使用
char *target = malloc(strlen(string1) + 1);。然后在strcat()之前使用target = realloc(target, strlen(string1) strlen(string2) + 1);
标签: c pointers char malloc string-concatenation