我试图用偏移量为2的第二个字符串覆盖第一个字符串的一部分.
这是我的第二个有效的try :
#include <stdio.h>
#include <string.h>
int main() {
char s[] = "Hello, World!";
char a[] = "aaa";
printf("%d\n", &s);
printf("%d\n", &s[2]);
memcpy(&s[2], a, sizeof(a)-1);
printf("%s\n", s);
return 0;
}
$ gcc -o test test2.c && ./test
520783106
520783108
Heaaa, World!
下面是我的第一次try ,它不起作用,在编译和段错误时发出警告:
#include <stdio.h>
#include <string.h>
int main() {
char s[] = "Hello, World!";
char a[] = "aaa";
printf("%d\n", &s);
printf("%d\n", sizeof(char)*2);
printf("%d\n", &s + (sizeof(char)*2));
memcpy(&s + (sizeof(char)*2), a, sizeof(a)-1);
printf("%s\n", s);
return 0;
}
$ gcc -o test test1.c && ./test
test1.c: In function ‘main’:
test1.c:12:4: warning: ‘memcpy’ writing 3 bytes into a region of size 0 overflows the destination [-Wstringop-overflow=]
12 | memcpy(&s + (sizeof(char)*2), a, sizeof(a)-1);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
test1.c:5:9: note: at offset 28 into destination object ‘s’ of size 14
5 | char s[] = "Hello, World!";
| ^
1547566642
2
1547566670
Hello, World!
Segmentation fault
谁能给我解释一下为什么Test1不起作用?
为什么1547566642和2的和等于1547566670而不是1547566644?
我想这是一个类型问题.SIZOF的回归是SIZE_T,但S是什么类型的?
首先要感谢您的帮助.;)