【发布时间】:2018-08-11 15:15:43
【问题描述】:
当双引号中的字符串作为参数传递给函数时,幕后会发生什么?为该字符串分配的内存在哪里?
如果我执行memcpy(ptr, "SINGH", strlen("SINGH")+1);,则输出仅为SINGH。多余的字节是从哪里复制的?
对于以下程序:
void func(char *ptr) {
memcpy(ptr, "SINGH", strlen("SINGH"));
cout << ptr << endl; /* Output is SINGHHELLO */
/* If I do memcpy(ptr, "SINGH", strlen("SINGH")+1); Output is SINGH only. From where does extra byte is copied from? */
}
int main() {
char str[11] = "HELLOHELLO";
char str2[10] = "ABC";
memcpy(str, "HELLO", strlen("HELLO")); /* Where is memory allocated for string 'HELLO' ? */
cout << str << endl << str2 << endl;
func(str);
return 0;
}
【问题讨论】:
-
C 或 C++ - 下定决心。
-
与任何 C 风格的数组一样,它被转换为指针。在这种情况下,指向第一个字符的
const char*指针。 -
编辑了我的问题 /* 如果我做 memcpy(ptr, "SINGH", strlen("SINGH")+1);输出仅为 SINGH。从哪里复制额外的字节? */ 与memcpy一起使用时,额外的字节从哪里复制?
-
"SINGH"是一个 6 个字符的数组,最后一个字符为空