Home > OS >  i have a confusion regarding the following code in c
i have a confusion regarding the following code in c

Time:10-18

//for the 1st code to print the value, we are using *ptr.

#include<stdio.h>
   int main(){
   int aadhar[5];
   int *ptr = &aadhar[0];

   printf("enter the numers");
   for(int i=0; i<5;i  ){
    scanf("%d",(ptr i));
   }
    for(int i=0; i<5;i  ){
    printf("%d\n",*(ptr i));
    }
    return 0;
}

but for the following code here, for printing we are not using * arr[I] or *ptr[i]. instead, we are using arr[i] or ptr[i].. what is the reason for that?

#include<stdio.h>

void printnumber( int arr[], int n);

int main(){
    int arr[]={1,2,3,4,5,6};
    printnumber(arr,6);
    return 0;

}
void printnumber(int *ptr, int n){
    for(int i=0; i<n; i  ){
        printf("%d\t",ptr[i]);  //why we are not using *ptr[i]?

    }
}

CodePudding user response:

This is because, *(ptr i) is the same as ptr[i]. They are the same.

*ptr[i] does not make sense here, as ptr[i] is of type int, not a pointer that you can use the unary * operator on. Quoting chapter 6.5.3.2,

The operand of the unary * operator shall have pointer type.

CodePudding user response:

because it's the pointer itself and from that reason he holds the adress. aahadr[i] should hold the values you are looking for.

  • Related