2

I am doing something like this;

int main()
{
    int *b[2], j;
    for (j = 0; j < 2; j++)
    {
        b[j] = (int *)malloc(12 * sizeof(int));
    } 
    return 0;
}

Please tell me what this instruction really means? And how can I pass this array of pointers to a function to access values like *(B[0]+1),*(B[1]+1) etc?

0x4d45
  • 704
  • 1
  • 7
  • 18
  • 2
    Don't [cast the result of malloc](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Cid Jan 14 '20 at 13:46
  • 3
    *Please tell me what this instruction really means?* which one ? – Cid Jan 14 '20 at 13:46
  • 1
    `*(B[0]+1)` can be written as `B[0][1]`. – dbush Jan 14 '20 at 13:46
  • 1
    You are asking someone to explain your code to you? What have you tried to pass an array of pointers? – Scott Hunter Jan 14 '20 at 13:47
  • *"And how can I pass this array of pointers to a function"* -> `MyFunction(b);` – Cid Jan 14 '20 at 13:47
  • *"how can I pass this array of pointers to a function"* - the same way you pass an array of *anything* to a function. Declare the formal parameter as a pointer to base-type (here, it is `int **`) and pass the array id as the argument from the caller. – WhozCraig Jan 14 '20 at 14:03
  • I want to know what malloc function is doing there? Yes, I want someone to explain my code. That in what manner malloc will allocate memory after declaring array of two integer arrays. – Hritikesh Semwal Jan 14 '20 at 15:43

1 Answers1

2
int main(void)
{
    int *b[2], j; // initialization of an array of pointers to integers (size = 2)
    for (j = 0; j < 2; j++) // for each of the pointers 
    {
        b[j] = malloc(12 * sizeof (int)); // allocate some space = 12 times size of integer in bytes (usually 4)
    } 
    return 0;
}

If you want to pass this array to a function you can just pass b

foo(b);
Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Sinking
  • 95
  • 8
  • 4
    "size = 2" might be misleading; `sizeof b` would not yield 2. Perhaps "length" would be better, or just "an array of two pointers to `int`." – ad absurdum Jan 14 '20 at 13:59
  • 2
    Mentioning what will be the prototype of foo() will add more value to your answer. – MayurK Jan 14 '20 at 14:21