我正在尝试做以下事情:
#include <stdio.h>
typedef unsigned char Set[128];
Set A; //Global variable
void main()
{
A[0] = 1;
A[1] = 2;
A[2] = 3;
printf("%x, %x, %x\n", A, &A, &A[0]);
printf("%u, %u, %u\n", A[0], A[1], A[2]);
Set *p;
p = A; //Same result with: p = &A;
printf("%x, %x, %x\n", p, &p, &p[0]);
printf("%u, %u, %u\n", p[0], p[1], p[2]);
}
第一次和第三次打印很好 - 我看到了两个变量的地址,对于“p”,它指向的地址。 我希望“p”指向“A”,这样我就可以通过“p”访问“A”数组中的值,但它不起作用——第四次打印时的值不像第二,它不打印数组的值。 如何创建指向“Set”变量类型的指针?
最佳答案
您为提供的参数类型使用了许多错误/不匹配的格式说明符。这导致 undefined behavior .
请记住,对于指针类型,您必须使用 %p
格式说明符,如果指针不是指向 char
类型的指针,您必须将void *
的参数。
关于上面关于转换要求的说法,引用章节§6.2.5/P28,
A pointer to void shall have the same representation and alignment requirements as a pointer to a character type. [....]
和脚注 48,
The same representation and alignment requirements are meant to imply interchangeability as arguments to functions, return values from functions, and members of unions.
话虽如此,请始终注意类型!!
在你的代码中,
A
是unsigned char [128]
类型(数组),- 和
p
的类型是unsigned char (*) [128]
。
因此,p = A;
不是有效的语句,因为类型不兼容。您必须使用 A
的地址才能使语句有效,例如
p = &A; // now the types are compatible
关于c - 指向数组的 typedef 的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48023931/