Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

As I am just a learner, I am confused about the above question. How is a pointer to an array different from array of pointers? Please explain it to me, as I will have to explain it to my teacher. Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

Pointer to an array

int a[10];
int (*ptr)[10];

Here ptr is an pointer to an array of 10 integers.

ptr = &a;

Now ptr is pointing to array of 10 integers.

You need to parenthesis ptr in order to access elements of array as (*ptr)[i] cosider following example:

Sample code

#include<stdio.h>
int main(){
  int b[2] = {1, 2}; 
  int  i;
  int (*c)[2] = &b;
  for(i = 0; i < 2; i++){
     printf(" b[%d] = (*c)[%d] = %d
", i, i, (*c)[i]);
  }
  return 1;
}

Output:

 b[0] = (*c)[0] = 1
 b[1] = (*c)[1] = 2

Array of pointers

int *ptr[10];

Here ptr[0],ptr[1]....ptr[9] are pointers and can be used to store address of a variable.

Example:

main()
{
   int a=10,b=20,c=30,d=40;
   int *ptr[4];
   ptr[0] = &a;
   ptr[1] = &b;
   ptr[2] = &c;
   ptr[3] = &d;
   printf("a = %d, b = %d, c = %d, d = %d
",*ptr[0],*ptr[1],*ptr[2],*ptr[3]);
}

Output: a = 10, b = 20, c = 30, d = 40


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...