Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ELI5: What is the data type of `int *p[]`

I don't understand what the datatype of this is. If its a pointer or an array. Please explain in simple terms. To quote what was in the book-

If you want to pass an array of pointers into a function, you can use the same method that you use to pass other arrays—simply call the function with the array name without any indexes. For example, a function that can receive array x looks like this:

void display_array(int *q[])
{
  int t;
  for(t=0; t<10; t++)
    printf("%d ", *q[t]);
}

Remember, q is not a pointer to integers, but rather a pointer to an array of pointers to integers. Therefore you need to declare the parameter q as an array of integer pointers, as just shown. You cannot declare q simply as an integer pointer because that is not what it is.

cite: C++: The Complete Reference, 4th Edition by Herbert Schildt, Page 122-123

like image 591
Abhyas29 Avatar asked Dec 05 '25 23:12

Abhyas29


2 Answers

This is how it's built up:

  • int is the type "int".
  • int* is the type "pointer to int"
  • int* [] is the type "array (of unknown bound/length) of pointer to int"
  • int* p[] is the declaration of a variable or parameter named p of the type above.
like image 118
palotasb Avatar answered Dec 08 '25 13:12

palotasb


... pointer to an array of pointers to integers

No it's not. q is the type int *[]. Which is an invalid (or possibly incomplete, depending on context) type in C++, and only valid in some places in C. Arrays must have a size.

The type int *[] is an (unsized) array of pointers to int. It is itself not a pointer.


The confusion probably comes from the fact that an array can decay to a pointer to its first element.

For example, lets say we have this array:

int a[20];

When plain a is used, it decays to a pointer to its first element: a is equal to &a[0].

like image 42
Some programmer dude Avatar answered Dec 08 '25 13:12

Some programmer dude