c - 指向数组的 typedef 的指针

标签 c arrays pointers types typedef

我正在尝试做以下事情:

#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.


话虽如此,请始终注意类型!!

在你的代码中,

  • Aunsigned 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/

相关文章:

java - 从数组实例调用 get(数组静态方法)

ios - 使用 2 个排序描述符对数组进行排序

objective-c - 这安全吗? (指向 Objective C 实例变量的指针)

c - 如何打印句子是否是 pangram。我在 c 中超时

c - 如何从 C 运行外部程序并解析其输出?

javascript - 为什么我的返回值中出现逗号? JavaScript 名人姓名揭晓器

c - 使用指向单个值的指针作为数组

C++ 指针 : changing the contents without changing the address?

ios - 在 macOS 中创建 C 定时器

c - 程序运行然后说它停止工作