Reputation: 21
I'm trying to create an array of pointers. In this code, array 'p' is supposed to contain pointers to the other arrays 'a', 'b', and 'c'. I can't figure out what is wrong with my code. Any help?
#include <stdio.h>
int main() {
int a[3]={'4','1','3'};
int b[3]={'a','1','3'};
int c[3]={'y','1','3'};
int *p[2];
p[1]=a[1];
*(p+1)= a+1;
printf("%d",p[1]);
return 0;
}
Upvotes: 1
Views: 60
Reputation: 310950
To declare an array of pointers to these arrays
int a[3]={'4','1','3'};
int b[3]={'a','1','3'};
int c[3]={'y','1','3'};
you need to write
int * p[3] = { a, b, c };
In this declaration the array designators used as initializers are implicitly converted to pointers to their first elements. That is it is the same if to write
int * p[3] = { &a[0], &b[0], &c[0] };
This expression statement
p[1]=a[1];
is incorrect because the left side operand has the type int *
while the right side operand has the type int
.
This statement
*(p+1)= a+1;
that is equivalent to the statement
p[1] = a + 1;
or to
p[1] = &a[1];
is correct.
In this statement
printf("%d",p[1]);
there is used an incorrect conversion specifier %d
with pointer expression p[1]
.
If you want to output the pointer expression p[1]
then you need to write
printf( "%p\n", ( void * )p[1] );
If you want to output the pointed value by the expression p[1]
you need to write
printf( "%d\n", *p[1] );
Or if you want to output it as a character you can write
printf( "%c\n", *p[1] );
Upvotes: 4