I've lied to the compiler and now it won't trust me

From: Adam Warner (usenet_at_consulting.net.nz)
Date: 02/04/05


Date: Fri, 04 Feb 2005 23:14:07 +1300

Hi all,

When adding variable length arrays to my program I created the elements as
type struct o *. This is because /most/ of the time the VLAs contains
pointers to struct o objects (these objects are as stringently aligned as
any C type in the implementation). Occasionally a single element is
actually a pointer to another VLA of pointers to struct o objects (and
occasionally I'm storing an integer index (of type ptrdiff_t) as an
immediate object).

Casting a pointer to an integer is no problem. But GCC will not compile my
program when I tell it that an element of an array is actually a pointer
to the same type of array:

void heap_trace_stack(struct o **ret0) {
  //Follow local variables
  if (ret0[-2]!=NULL) {
    struct o **var=(struct o **) *ret0[-2]; //Line 207
    index num_var=(index) var[0];
    ...
  }
  ...
}

The code above has been passed a VLA offset to the first element of a
particular category (&ret0[0]). If the element at the legal index position
-2 is not NULL then it's actually a pointer to another VLA of the same
type. The line 207 cast is rejected by GCC as an error (gcc-3.4 -std=c99
-O2 -Wall):

heap.c: In function `heap_trace_stack':
heap.c:207: error: cannot convert to a pointer type

If I have to change the VLAs to elements of type void ** then I'll have to
declare many variables as pointers (to pointers ...) to void; and castings
to struct o * will cascade though the program and it will become far less
type safe as a whole.

Perhaps this is the C way. Advice appreciated.

Regards,
Adam



Relevant Pages

  • Re: Passing an array of structuresfrom a pointer?
    ... an array of struct. ... You cannot assign a pointer to struct to a long* ... to only declare structs in headers and then define the ...
    (microsoft.public.vc.language)
  • Re: Looking for a more elegant way to do memory offsets
    ... The mallocfunction returns memory that is "suitably aligned" ... >which in it contains the pointer to the first element in the linked ... and here a "struct dem_mem" does not contain a pointer to another ... This is not a linked-list access, but rather an array access: ...
    (comp.lang.c)
  • Re: Passing an array of structuresfrom a pointer?
    ... to only declare structs in headers and then define the ... the struct should be declared ... what if you have a simple array like this: ... It also returned the value of the pointer. ...
    (microsoft.public.vc.language)
  • Re: I went a help
    ... int main{ ... nig is an array of struct. ... Since name is a pointer, ...
    (comp.lang.c)
  • Re: Pointer to array of structs?
    ... I have made a struct. ... Now I would like to make a pointer an array with 4 ... int main ...
    (comp.lang.c)