【发布时间】:2017-01-28 11:38:18
【问题描述】:
我在这个线程中阅读了 C 中的整数指针减法:Pointer subtraction confusion,它很简单,可以掌握和测试。
但是,我尝试使用 char* 复制类似的场景,但我得到的结果没有多大意义。
这是我尝试过的场景:
#include <stdio.h>
#include <string.h>
int main() {
char a_arr[16] = "";
char *a = a_arr;
char b_arr[1] = "";
char *b = b_arr;
printf("\nThe amount by which they differ is: %d\n", a-b);
// a-b = 1, which makes sense since they are 1 char away
return 0;
}
接下来我尝试的是我无法理解的内容
#include <stdio.h>
#include <string.h>
int main() {
char a_arr[16] = "";
char *a = a_arr;
char b_arr[2] = "";
char *b = b_arr;
printf("\nThe amount by which they differ is: %d\n", a-b);
// a-b = 16, which doesn't really make sense to me..
return 0;
}
我的猜测是编译器端有一些填充内容,我认为不应该是这种情况,因为它是一个 char 数组并且不需要对齐..
我不确定为什么它是 16 字节。非常感谢任何帮助!
我使用下面的在线界面编译并运行了这段代码: http://www.tutorialspoint.com/compile_c_online.php
【问题讨论】:
-
您调用了未定义的行为。两个指针必须指向同一个数组! (或正好过去)您期望减去两个完全不相关的指针会得到什么?什么是“1升减2秒”?
-
@Olaf 是不是和“1 公斤减 2 英里”的结果一样?
-
@SouravGhosh 更像是“1000 安培 - 10 伏”
-
@Olaf 或者“5 页负 178 度”
-
@SouravGhosh:如果 OP 只是摇头或开始思考并对我的第一条评论进行一些研究(关于类比的内容较少,但第一部分),我会感到很受伤。
标签: c pointers pointer-arithmetic