arrays and pointers

I have a simple question well it's probably a simple question how come when initializing a pointer to an array you do not have to put the address of sign before it for example
1
2
3
4
 int ray[3];
 int *p;
 p = ray;


while this would not be valid if you were to do the same thing with an int or a char

also a a side question on pointers an arrays

how come you can pass an array in by just using a pointer??
1
2
3
4
5
6
 
  int function(int *passAray){

     // do something
  }


and also pass it in like a normal array

1
2
3
4
5
6

 int function(int passAray[]){

     // do something
  }
 


whats the difference between them two and how is the first one even valid?
Last edited on
Hi,
When you declare an array of unknown size (int arr[]) (especially as a function parameter), it just behaves exactly like a pointer (int *arr). So these two ways of writing function parameters can be used interchangeably (Though you can't just repeat the [] part more than once)

However, (arr[]) has a different meaning if you use it elsewhere, and it behaves exactly like an array. Only that the exact size of the array is not told. That's why you must initialize the array with values and the size of the array will be determined by the number of values it can find during its initialization.

1
2
3
4
5
6
7
8
9
int foo[] = {1, 2, 3}; // 3 values - foo array has 3 elements
std::string bar[] = 
{
    "red",
    "blue",
    "gray",
    "pink",
    "cyan" // 5 values - bar array has 5 elements
};
Last edited on
Topic archived. No new replies allowed.