Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

c - Pointer to an array and Array of pointers

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...