-2

I was wondering how I would access a double pointer inside of a struct, for example:

typedef struct Example {
   char **set;
   int size;
 }Example;

The struct is called inside the function as:

struct Example exmpl;

If I needed to create a new array within that array of arrays, how would I call it in a function/main? Or is it just the same as regular, exmpl->set?

Daniel
  • 21,933
  • 14
  • 72
  • 101

1 Answers1

0

It doesn't matter what the type of set is, you access it with exmpl.set. If you need to access a single element it would be exmpl.set[0][0] for example.

If you need to allocate memory for it, you need to allocate memory for the outer array and then for each inner array independently, like this to create an array of 10x20:

struct Example exmpl;
exmpl.set = malloc(10 * sizeof(char*));       // 10 "arrays" in the set
for (int i = 0; i < 10; i++)
    exmpl.set[i] = malloc(20 * sizeof(char)); // 20 chars within each "array"

Then for setting each element's value:

for (int i = 0; i < 10; i++)
    for (int j = 0; j < 20; j++)
        exmpl.set[i][j] = calculate(i, j);

And, an array and a pointer are different, so what you have here is a pointer to a pointer to char (which works similarly to a 2-dimensional array of chars)

Daniel
  • 21,933
  • 14
  • 72
  • 101
  • 1
    [Concerning casting the result of `malloc()`](https://stackoverflow.com/q/605845/2410359) – chux - Reinstate Monica Sep 24 '17 at 04:01
  • Don't forget to set `exmpl.size = 10;` too. – Jonathan Leffler Sep 24 '17 at 04:24
  • Thanks for pointing me in the right direction! Would I still need to use the for loop even if its an array of strings? – Olivia Garcia Sep 24 '17 at 05:27
  • **For creation:** it depends on how you construct your strings, remember they need to live somewhere in memory, how are you constructing them? **For setting each element's value:** you'll still need the outer-most loop, but not the inner-most one because you can use things like `strcpy` which do the char-by-char copy for you (or you can just copy the pointer if the strings live somewhere else in memory). – Daniel Sep 24 '17 at 06:10