+ 1
why does *A is required i mean why is pointer needed here....plz answer....
#include<stdio.h> void printArray(int *A, int n){ //i am talking about this *a for (int i = 0; i < n; i++) { printf("%d ", A[i]); } printf("\n"); } int main(){ int A[] = {1, 2, 5, 6, 12, 54, 625, 7, 23, 9, 987}; int n = 11; printArray(A, n); return 0; }
1 Odpowiedź
+ 3
When you assign an array to a variable, you actually assign the pointer to the first element of the array. To test this, run the following lines
int arr[] = { 1, 2, 3 };
cout << *arr;
// Outputs 1 because arr is actually pointer to first element (1) of the array
So when you pass an array to a function, and in your case, when you pass `A` to `printArray`, actually the pointer to the first element of the array is passed. That is why you are able to recieve an array in a function where `int *` is required.
NOTE: it is not compulsory to specify the type of parameter `A` as `int *`. You can also use `int A[]`. So your function can also be defined as
void printArray(int A[], int n) {
......
}