0

This question builds up on my previous question: Difference Between *list and **list. I decided to split them into two questions to make it less confusing, clear, and fair for people answering.

I have this code:

typedef struct A
{
   char c[100];
}A;

listSize = 5000; 

A *list = malloc(listSize * sizeof(*list));

I want to call a function and create a pointer for every element.

How would I create 5000 pointers and make them point to the elements on the list?

p0 -> list[0]
p1 -> list[1]
..
..
p[n] -> list[n]
Community
  • 1
  • 1
Mike John
  • 818
  • 4
  • 11
  • 29

2 Answers2

4
A** p = malloc(listSize * sizeof(A*));
int i;
for(i = 0; i < listSize; ++i) {
    p[i] = &list[i];
}
timrau
  • 22,578
  • 4
  • 51
  • 64
0
typedef struct A
{
   char c[100];
}A;

size_t listSize = 5000; // !

A *list = malloc(listSize * sizeof(*list));
if (!list) {
    // complain about low memory and leave this part of function.
}

A** p = malloc(listSize * sizeof(A*));
if (!p) {
    // complain about low memory and leave this part of function.
    // Maybe free(list) in order not to leak memory.
}

Only then it is safe to write to p:

size_t i;
for(i = 0; i < listSize; ++i) {
    p[i] = &list[i];
}
glglgl
  • 89,107
  • 13
  • 149
  • 217