C 关于矩阵的指针算法的指针
我对C中指针运算的指针有疑问。C 关于矩阵的指针算法的指针,c,pointers,C,Pointers,我对C中指针运算的指针有疑问。 如果我们这样做 int ** ptr = 0x0; printf("%p",ptr+=1); 输出将是ptr+(在我的例子8中,存储指针所需的字节数)。 现在,如果我们声明一个矩阵: int A[100][50]; A[0]是指针的指针。 A[0]+1现在将指向[0]+(#存储整数所需的字节数,在我的例子4中)。 为什么“通常”添加8个字节,而现在添加4个? A[0]+1将指向A[0][1],因此它很有用,但它是如何工作的? 谢谢大家! 考虑在64位机器上运
如果我们这样做
int ** ptr = 0x0;
printf("%p",ptr+=1);
输出将是ptr+(在我的例子8中,存储指针所需的字节数)。现在,如果我们声明一个矩阵:
int A[100][50];
A[0]
是指针的指针。
A[0]+1
现在将指向[0]+(#存储整数所需的字节数,在我的例子4中)。
为什么“通常”添加8个字节,而现在添加4个?
A[0]+1
将指向A[0][1]
,因此它很有用,但它是如何工作的?谢谢大家! 考虑在64位机器上运行的这个程序(一个运行macOS Mojave 10.14.6的Mac,准确地说是GCC 9.2.0): 因此,可以推断,
A[0]
是一个50int
的数组-它不是“指针的指针”。然而,当在表达式(如A[0]+1
)中使用时,它会“衰减”为“指向int
”的指针(指向数组元素类型的指针),因此A[0]+1
在数组中是一个整数
输出的最后一块显示数组的地址具有不同的类型-
int(*)[50]
,如果a[0]
a[0]
不是指针的指针。它衰减为int*
ptr
指向大小为*ptr
=int*
的元素,并且A[0]
作为指向大小为*A[0]
=int
的元素的指针。
#include <stdio.h>
int main(void)
{
int A[100][50];
printf("Size of void * = %zu and size of int = %zu\n", sizeof(void *), sizeof(int));
printf("Given 'int A[100][50];\n");
printf("Size of A = %zu\n", sizeof(A));
printf("Size of A[0] = %zu\n", sizeof(A[0]));
printf("Size of A[0][0] = %zu\n", sizeof(A[0][0]));
putchar('\n');
printf("Address of A[0] = %p\n", (void *)A[0]);
printf("Address of A[0] + 0 = %p\n", (void *)(A[0] + 0));
printf("Address of A[0] + 1 = %p\n", (void *)(A[0] + 1));
printf("Difference = %td\n", (void *)(A[0] + 1) - (void *)(A[0] + 0));
putchar('\n');
printf("Address of &A[0] = %p\n", (void *)&A[0]);
printf("Address of &A[0] + 0 = %p\n", (void *)(&A[0] + 0));
printf("Address of &A[0] + 1 = %p\n", (void *)(&A[0] + 1));
printf("Difference = %td\n", (void *)(&A[0] + 1) - (void *)(&A[0] + 0));
return 0;
}
Size of void * = 8 and size of int = 4
Given 'int A[100][50];
Size of A = 20000
Size of A[0] = 200
Size of A[0][0] = 4
Address of A[0] = 0x7ffee5b005e0
Address of A[0] + 0 = 0x7ffee5b005e0
Address of A[0] + 1 = 0x7ffee5b005e4
Difference = 4
Address of &A[0] = 0x7ffee5b005e0
Address of &A[0] + 0 = 0x7ffee5b005e0
Address of &A[0] + 1 = 0x7ffee5b006a8
Difference = 200