
Dynamically allocated array of pointers and their usage.
Hello. I have a concept to dynamic allocate an array of pointers but so
far I have not been able to implement it in C. The purpose of this array
is to reference a list of a given data type. This is similar to linked
list but instead moving up and down the list you may simply access a
given element through an array pointer.
Example - A list of variable length strings.
array of pointers to list
---------
| 0 | 3 | 6 | 9 | <- address values
---------
array of data
0 1 2 3 4 5 6 7 8 9 10 addresses
-----------------------
| A | B | 0 | C | D | 0 | E | F | G | 0 |
-----------------------
So how can this be done in C? Below are a few of my attempts but they
don't compile correctly.
#include <stdio.h>
#include <malloc.h>
#define STRING_SIZE 4
#define STRINGS 4
int main()
char i;
int h,g;
void *pointers;
char *data;
pointers = malloc(sizeof(pointers) * STRINGS);
data = malloc(STRING_SIZE * STRINGS);
/* Given data some data */
for(i = 'A'; i <= 'Q'; i++)
{
data[i] = i;
}
/* Assign the address of every 4th element in data to pointers */
for(h = 0, g = 0; h <= STRING_SIZE * STRINGS; h =+ 4, g++)
{
/* This is the part I'm stuck on. What I want is to copy the
address of a data array element to the array of pointers but I can't get
a correct syntax.
is it
pointers[g] = &data[h];
or
*(pointers + g) = (void *) &data[h] ;
These all gave me errors. Does any one know how to do this?
*/
Quote:
}
free(pointers);
free(data);
return 0;
Quote:
}