1

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;
}

1
  • For starters, int *p[2]; --> int *p[3]; This won't even compile: p[1] = a[1]; because a[1] is an int and p[1] is an int *. What about: int *p[3]; p[0] = a; p[1] = b; p[2] = c;? Commented Feb 15, 2022 at 19:05

1 Answer 1

4

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] );
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I took your suggestions and the program prints out 49, how do i just print out the 4?
@BersabehKifle It is the ASCII value of the character '1' stored in a[1]. To output it as a character you could write printf( "%c\n", *p[1] );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.