How do I cast a pointer to a dynamic sized pointer to an array?

I want to be able to reference a variable sized array with a global pointer. But which one do I use a pointer that will work with variable array sizes? In the example below, assume N will only be known at runtime (could be an argument, for example), so compiling temporary solutions won't work.

What I want to achieve:

main.c

some_sort_of_pointer *x;

main()
{
    int N=256; //or N=64 or whatever
    char (*LC)[N];

    LC=malloc(1024);
    x=LC;
    memcpy(x[2],"hello world",11);
    x[0][176]=123;

    dostuff();
}

      

I'm sure there is a simple obvious way to do this, but I can't nail it down. My first attempt to ask this was confusion, so this time I hope it is clear what I want to achieve.

OS Centos 6.5

GCC compiler 4.8 (using C99)

+3


source to share


2 answers


As with compile time, the type to reference is not specified, a pointer can help void

.

However, it is not enough to store a non-food reference (which void *

it actually is) as it is important to know the size of the array (VL). Thus, the latter must also be stored globally as it cannot be pulled out of said memory.

An example of how this can be achieved is given below:

main.h:

#include <stdlib.h> /* for size_t */

struct VLA_descriptor
{
  void * p;
  size_t s;
} 

extern struct VLA_descriptor vla_descriptor;

      

foo.h:



void foo(void);

      

foo.c:

#include "main.h"
#include "foo.h

void foo(void)
{
  char (*p)[vla_descriptor.s] = vla_descriptor.p;

  /* Do something with the VLA reference p. */
}

      

main.c:

#include "main.h"
#include "foo.h"

struct VLA_descriptor vla_descriptor = {0};

int main(int argc, char ** argv)
{
  size_t s = atoi(argv[1]);
  char (*p)[s] = malloc(s);

  vla_descriptor.p = p;
  vla_descriptor.s = s;

  foo();

  ... /* Free stuff and return. */
}

      

Error checking has been omitted in this code example for readability.

+2


source


With a lot of thanks to @alk (and to everyone who answered), I think I will have the closest I am going to figure out what I am looking for:

void *LC
int LCS;
int main(int argc, char **argv) {
    LCS=256;
    LC=malloc(1024)
    memcpy(((char(*)[LCS])LC)[2],"hello world",11);
    ((char(*)[LCS])LC)[0][176]=123;
    printf("%d %s\n",((char(*)[LCS])LC)[0][176],&((char(*)[LCS])LC)[2]);
}

      



((char(*)[LCS])LC)

is the equivalent of what I wanted. It is similar to @alk's idea and requires 2 globals, but that means I can use it in functions without declaring a new variable. I sent @alk back with the answer as what he wrote gave me 90% of what I needed.

Although, if someone can reduce ((char(*)[LCS])LC)

to one global, I'd love to see it :)

0


source







All Articles