C 每次更改字符指针的内容时,是否需要更改其大小?
我将目标的大小定义为string1的大小。然后我将string2添加到目标。我没有增加目标的大小。为什么我的代码仍然有效C 每次更改字符指针的内容时,是否需要更改其大小?,c,pointers,char,malloc,string-concatenation,C,Pointers,Char,Malloc,String Concatenation,我将目标的大小定义为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"; st
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)
应该返回什么?你试过了吗?你知道和的区别吗?顺便说一下,sizeof(string1)
将返回指向字符的指针的字节大小,通常为4个字节strcat()
如果它“工作”了几次,并不意味着代码是正确的。你必须明白,你正在一块没有分配的内存中写入信息。它之所以有效,是因为你很幸运。写过缓冲区的末尾是一种很好的方法,它会损坏缓冲区后面的数据,并导致程序以令人讨厌的方式崩溃 其实你第一次也很幸运。Sizeof返回变量类型的大小,即指针,而不是字符串的长度。即使您使用了strlen(string1),您也必须添加1,以便为终止字符串的空字符留出空间 C会让你自食其力。您有责任确保您没有这样做,和/或使用
lint
等工具对代码运行附加测试,以捕获其他语言经常检查的一些错误。(或者以更高的警告级别运行编译器。)
另一方面,当你真的想在C中作弊时,能够在C中作弊是它强大的原因之一——就像汇编代码一样,如果你知道自己在做什么,你就可以打破规则去做一些本来很难做到的事情。这是一把锋利的刀。小心知道你周围的情况,以防出错。你的代码从头到尾都是错误的。sizeof(string1)是4(取决于机器),因为指针存储为整数。使用
char*target=malloc(strlen(string1)+1)代码>。然后在strcat()之前使用target=realloc(target,strlen(string1)strlen(string2)+1)代码>