初始化结构并通过引用传递

initialising structs and passing by reference

我是 C 的新手,在使用结构时遇到问题。我有以下代码:

typedef struct uint8array {
 uint8 len;
 uint8 data[];
} uint8array;

int compare_uint8array(uint8array* arr1, uint8array* arr2) {
  printf("%i %i\n data: %i, %i\n", arr1->len, arr2->len, arr1->data[0], arr2->data[0]);
  if (arr1->len != arr2->len) return 1;
  return 0;
  }

int compuint8ArrayTest() {
 printf("--compuint8ArrayTest--\n");
 uint8array arr1;
 arr1.len = 2;
 arr1.data[0] = 3;
 arr1.data[1] = 5;    

 uint8array arr2;
 arr2.len = 4;
 arr2.data[0] = 3;
 arr2.data[1] = 5;    
 arr2.data[2] = 7;    
 arr2.data[3] = 1;    

 assert(compare_uint8array(&arr1, &arr2) != 0);
}

现在这个程序的输出是:

 --compuint8ArrayTest--
 3 4
 data: 5, 3

为什么这些值不是我初始化的值?我在这里错过了什么?

在您的例子中,uint8 data[];flexible array member。您需要先为 data 分配内存,然后才能实际访问它。

在您的代码中,您试图访问无效的内存位置,导致 undefined behavior

引用 C11,章节 §6.7.2.1(强调我的

As a special case, the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member. In most situations, the flexible array member is ignored. In particular, the size of the structure is as if the flexible array member were omitted except that it may have more trailing padding than the omission would imply. Howev er, when a . (or ->) operator has a left operand that is (a pointer to) a structure with a flexible array member and the right operand names that member, it behaves as if that member were replaced with the longest array (with the same element type) that would not make the structure larger than the object being accessed; the offset of the array shall remain that of the flexible array member, even if this would differ from that of the replacement array. If this array would have no elements, it behaves as if it had one element but the behavior is undefined if any attempt is made to access that element or to generate a pointer one past it.

在第 6.7.2.1 章中也可以找到正确的用法示例

EXAMPLE 2 After the declaration:

struct s { int n; double d[]; };

the structure struct s has a flexible array member d. A typical way to use this is:

int m = /* some value */;
struct s *p = malloc(sizeof (struct s) + sizeof (double [m]));

and assuming that the call to malloc succeeds, the object pointed to by p behaves, for most purposes, as if p had been declared as:

struct { int n; double d[m]; } *p;